The methods of the java.io.FileWriter class are similar to the methods of java.io.OutputStream class.
The java.io.FileWriter class writes text files, using the platform’s default character encoding and the buffer size. If you need to change these values, you can use the OutputStreamReader on a FileOutputStream. FileWriter object can be created by passing either a File object or a filename or a file descriptor as shown below:
Here is a list of commonly used methods for FileWriter class:
write(String) Writes a String to the output stream
write(char ) Writes an array of characters to the output stream
flush() Clears all the buffers in a chain of Writer and OutputStream
close() Closes the output stream, flushing it first.
The java.io.OutputStreamWriter class connects byte streams and character streams.
Here is an example showing how to read a text file line by line and writing it to another text file, using FileReader, BufferedReader, FileWriter, and BufferedWriter:
public class reader
public static void main (String args)
FileReader input = new FileReader("Demo.txt");
BufferedReader bufferInput = new BufferedReader(input);
FileWriter output = new FileWriter("Demo1.txt");
BufferedWriter bufferOutput = new BufferedWriter(output);
while ((line = bufferInput.readLine()) != null)
System.out.println("Read: " +line);
bufferOutput.write (line, 0, line.length());
catch (IOException e)
This code is similar to the code written above for reading a file; but here the file is read line by line and the output is written to the console and to another text file. After creating a FileReader and a BufferedReader object for reading the text file, a FileWriter object output is created, using the constructor FileWriter(“Demo2.txt”), where Demo2.txt is a text file, which will be written into. BufferedWriter object is created for writing the output to the file “Demo2.txt”. Using BufferedWriter’s write() method, content of the “Demo.txt” is written into the “Demo2.txt”.