Java Reference
In-Depth Information
Solution
Construct a FileReader , FileWriter , FileInputStream , or FileOutputStream .
Discussion
The action of constructing a FileReader , FileWriter , FileInputStream , or FileOut-
putStream corresponds to the “open” operation in most I/O packages. There is no explicit
open operation, perhaps as a kind of rhetorical flourish of the Java API's object-oriented
design. Therefore, to read a text file, you'd create, in order, a FileReader and a
BufferedReader . To write a file a byte at a time, you'd create a FileOutputStream and
probably a BufferedOutputStream for efficiency:
// OpenFileByName.java
BufferedReader is = new BufferedReader(new FileReader("myFile.txt"));
BufferedOutputStream bytesOut = new BufferedOutputStream(
new FileOutputStream("bytes.dat"));
...
bytesOut.close( );
Remember that you need to handle IOException s around these calls.
Copying a File
Problem
You need to copy a file in its entirety.
Solution
Use a pair of Stream s for binary data, or a Reader and a Writer for text, and a while loop
to copy until end-of-file is reached on the input.
Search WWH ::




Custom Search