Recipe 10.6 Opening a File by Name


The Java documentation doesn't have methods for opening files. How do I connect a filename on disk with a Reader, Writer, or Stream?


Construct a FileReader , FileWriter, FileInputStream, or FileOutputStream.


The action of constructing a FileReader, FileWriter, FileInputStream, or FileOutputStream 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. So 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:

// BufferedReader is = new BufferedReader(new FileReader("myFile.txt")); BufferedOutputStream bytesOut = new BufferedOutputStream(     new FileOutputStream("bytes.dat")); ... bytesOut.close( );

Remember that you need to handle IOExceptions around these calls.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: