- Details
- Written by Nam Ha Minh
- Last Updated on 28 July 2019   |   Print Email
In Java, the
FileReader and
FileWriter classes are designed for reading and writing text files at low level, i.e. reading and writing a single character or an array of characters at once.
1. Creating a FileReader object
You can create a new object of the
FileReader class by supplying the file path either as a
String or a
File object. For example:
try {
FileReader reader1 = new FileReader("/path/to/yourfile1.txt");
File file = new File("/path/to/yourfile2.txt");
FileReader reader2 = new FileReader(file);
// code to read…
} catch (FileNotFoundException ex) {
System.err.println(ex);
}
As you can see, these
FileReader contructors throw
FileNotFoundException if the file does not exist or is a directory.
2. Reading Characters from a File
The
FileReader class inherits 4 different read methods from the
Reader and
InputStreamReader:
- int read(): reads a single character, and returns the character as an integer value.
- int read(char[] cbuf): reads characters to an array, and returns the number of characters read.
- int read(char[] cbuf, int offset, int length): reads characters to a portion of an array, and returns the number of characters read.
- int read(CharBuffer target): reads characters into a character buffer, and returns the number of characters added to the buffer.
All these read methods return -1 if the end of the stream has been reached, and throw
IOException if an I/O error occurs.After the reading is finished, you should close the reader by calling its
close() method. If you use the reader within a try-with-resources structure, the Java compiler will generate the close call for you.Let’s see an example.
The following code reads a text file character by character and prints the content of the file to the standard output:
try (
FileReader reader = new FileReader("FileReaderExamples.java")
) {
int charRead = -1;
while ((charRead = reader.read()) != -1) {
System.out.print((char) charRead);
}
} catch (FileNotFoundException ex) {
System.err.println("File not found error: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
3. Creating a FileWriter object
You can create a new object of the
FileWriter class by supplying the file path either as a
String or a
File object, and specify whether to append data to the end of an existing file or write data from the beginning. For example:
try {
FileWriter writer1 = new FileWriter("path/to/your/file1.txt");
File file = new File("path/to/your/file2.txt");
FileWriter writer2 = new FileWriter(file);
// code to write...
} catch (IOException ex) {
System.err.println(ex);
}
As you can see, these
FileWriter contructors throw
IOException if an I/O error occurs, e.g. the file does exist but is a directory.The following code creates a new
FileWriter object to append data to an existing file:
try {
File file = new File("path/to/your/file.txt");
boolean append = true;
FileWriter writer = new FileWriter(file, true);
// code to write...
} catch (IOException ex) {
System.err.println(ex);
}
4. Writing Characters to a File
The
FileWriter class inherits the following write methods from its super classes
Writer and
OutputStreamWriter:
- write(int c): writes a single character.
- write(char[] cbuf): writes an array of characters.
- write(char[] cbuf, int offset, int length): writes a portion of an array of characters.
- write(String str): writes a String.
- write(String str, int offset, int length): writes a portion of a String.
These writing methods throw
IOException if an I/O error occurs.After the writing is finished, you should close the writer by calling its
close() method. If you use the writer within a try-with-resources structure, the writer is closed implicitly.Let’s see an example. The following code opens a text file for writing a String, append to the end of the file if it already exists:
try (
FileWriter writer = new FileWriter(new File("Notes.txt"), true);
) {
writer.write("Java FileWriter Examples");
} catch (IOException ex) {
System.err.println(ex);
}
5. Java FileReader and FileWriter Examples
The
FileReader and
FileWriter classes are usually used together. The following example copies content of a text file to another, character by character:
try (
FileReader reader = new FileReader("Notes1.txt");
FileWriter writer = new FileWriter("Notes2.txt");
) {
int charRead = -1;
while ((charRead = reader.read()) != -1) {
writer.write(charRead);
}
} catch (IOException ex) {
System.err.println(ex);
}
Note that the
FileReader and
FileWriter classes are usually wrapped inside a
BufferedReader and
BufferedWriter for more efficiency.
API References:
Related Java File IO Tutorial:
Other Java File IO Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.