Byte streams vs Character streams

File copying with Character Streams

The files can be read with character streams also. In the following program, file to file copying is done with FileReader and FileWriter. It is equivalent to FileToFile1.java of byte streams copying.

import java.io.*;
public class FileToFile2
{
  public static void main(String args[]) throws IOException
  {
    FileReader fr = new FileReader("pqr.txt");  
    FileWriter fw = new FileWriter("xyz.txt");   
       
    int temp;
    while( ( temp = fr.read() ) != -1 )
    {
      fw.write(temp);   			// writes to xyz.txt
      System.out.print((char) temp);   	// at DOS prompt
    }
    fw.close();
    fr.close();
  }
}

FileReader fr = new FileReader("pqr.txt");
FileWriter fw = new FileWriter("xyz.txt");

The explanation of this program is the same of byte streams illustrated in FileToFile1.java. The pqr.txt is the source file opened with FileReader constructor in read mode. Similarly xyz.txt is the destination file opened with FileWriter constructor in write mode. In case of byte sterams, the classes used are FileInputStream and FileOutputStream.

FileWriter fw = new FileWriter("xyz.txt", true);

The optional second boolean parameter true opens the file, "xyz.txt", in append mode.

while( ( temp = fr.read() ) != -1 )

The read() method of FileReader reads one byte at a time from the source file, converts into ASCII (ASCII is a subset of Unicode) integer value and returns. For example if 'A' is there in the source file, the read() method reads it and converts to 65 and returns. The same method returns -1 if EOF is encountered while reading. That is, every byte read is checked against -1 and then control enters the loop.

fw.write(temp);
System.out.print((char) temp);

The write(temp) method of FileWriter takes the ASCII value, converts back to the original character and then writes to the destination file. To write to the DOS prompt with println() method, the ASCII value is converted to char explicitly and then written.

fw.close();
fr.close();

When the job is over, close the streams in the order of first writer stream and then reader stream to have proper flushing of data.

Note: If the streams are not closed properly, sometimes buffers (maintained internally by the system) are not cleared and thereby data will not be not seen in the destination file.

5 thoughts on “Byte streams vs Character streams”

  1. Hello, I try to learn Java and you said that “The read() method of FileReader reads one byte at a time” but if I look at the Oracle website they say about read() method of FileReader that “Reads a single character.” and about read() method of FileInputStream that “Reads a byte of data”…What exactly do this read() method?

Leave a Comment

Your email address will not be published.