Next: The PrintWriter class. Up: Text files. Previous: None.


FileReader and FileWriter classes

Earlier we saw the FileInputStream and FileOutputStream classes to work with files as a sequence of bytes. The java.io package also provides two other classes, FileReader and FileWriter, that work with files as a sequence of characters instead.

(This distinction between bytes and characters may seem a bit pedantic, given that the major operating systems of today use ASCII - and so characters and bytes are almost synonymous. But Java uses the Unicode character set (where a character is 16 bits long), and so it needs to distinguish the two concepts.)

FileReader class

The FileReader class works analogously to the FileInputStream class: The only change is that the read() method works with an array of characters, rather than an array of bytes.

FileReader(File file) throws FileNotFoundException
Creates a FileReader object for the specified file. (It throws FileNotFoundException if the specified file doesn't exist or isn't readable.)
int read(char[] ch) throws IOException
Attempts to fill the array ch with bytes from the file, returning the number of characters successfully read, or returning -1 if the end of the file has already been reached.
void close() throws IOException
Closes the file for reading, making further reads from the object invalid.

FileWriter class

Similarly, the FileWriter class works analogously to the FileOutputStream class, except that the write() methods work with arrays of characters. (Also, the FileWriter constructor method throws an IOException instead of a FileNotFoundException - it's a minor change, but it can affect the program code.)

FileWriter(File file) throws IOException
Creates a FileWriter object for the specified file. (It throws IOException if the specified file isn't writeable.)
void write(char[] ch) throws IOException
Writes the characters of ch into the file just after the location where it last wrote.
void write(char[] b, int offs, int num) throws IOException
Writes num characters from ch, beginning at index offs in the array, into the file just after the location where it last wrote.
void close() throws IOException
Closes the file, ensuring that everything is saved on the disk and making the object ineligible for use in further writes.


Next: The PrintWriter class. Up: Text files. Previous: None.