Java Reference
In-Depth Information
Buffering File Input and Output
The BufferedReader class does more than read the characters from a fi le line by line. It
buffers the characters to minimize the overhead of actually reading from the fi le system
each time a character is read. You can set the size of the buffer by using the following
BufferedReader constructor:
public BufferedReader(Reader in, int size)
Similarly, the BufferedWriter class is used to buffer characters written to a fi le and con-
tains the following constructor:
public BufferedWriter(Writer out, int size)
If you are working with other data types besides characters, use the FileOutputStream
and FileInputStream classes to read and write to the fi le, and use the BufferedInput-
Stream and BufferedOutputStream classes if you want to also buffer that data.
The File Class
The exam objectives mention using the java.io.File class in combination with the stream
classes. The File class represents the pathname of a fi le or directory, and the class contains
useful methods for determining information about the fi le or directory. Some uses of the
File class include the following:
Determining if a file exists using the exists method, which returns a boolean
Determining if a file can be read from, written to, or executed using the respective
canRead , canWrite , or canExecute methods
Creating a new file using the createNewFile method
Making a new directory using the mkdir method
Deleting a file or directory using the delete method
Listing the contents of a directory using the list and listFiles methods
To demonstrate using the File class, the following code creates a new fi le and writes strings
to it using a FileWriter object. The FileWriter is chained to a BufferedWriter , which in
turn is chained to a PrintWriter , a useful class for printing all data types. ( System.out is a
PrintWriter object.) Study the code and see if you can determine what it does:
1. package com.sybex.io;
2.
3. import java.io.*;
Search WWH ::




Custom Search