Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Opening a File by Name

Problem

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

Solution

Construct a FileReader , a FileWriter, a FileInputStream, or a FileOutputStream.

Discussion

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:

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

Remember that you will need to handle IOException around these calls.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata