File Copying FileReader FileWriter

File Copying FileReader FileWriter

We have seen earlier, clearly the style and basics of file copying in Java, with byte streams FileInputStream and FileOutputStream in "Semantics of File Copying" and the it&339;s drawbacks of file copying in "Performance drawbacks of file copying".

Now let us do the same job but with character streams – FileReader and FileWriter. The same previous program "FileToFile1.java" is modified to suit character streams. The same rules and explanation works here also.

Following program does File Copying FileReader FileWriter to copy file to file

.

File Copying FileReader FileWriter

Output screenshot on File Copying FileReader FileWriter

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

FileReader, being a reader class, opens the file "pqr.txt" in read mode and similarly FileWriter, being a writer class, opens the file "xyz.txt" in write mode.

k = fr.read()
fw.write(k);

read() method of FileReader reads one byte, at a time, from he source file "pqr.txt", converts it into ASCII integer value and returns. For example, if the character A exists in the source file, it is read, converted to 65 and returned. The write() method of FileWriter takes the integer value, converts back to the original character A and then writes to the destination file "xyz.txt".

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

When the job is over, close the stream objects (handles), first writer and then reader for proper flushing of data.

Two catch blocks are included to handle the exceptions thrown by different methods shown below.

  1. FileReader constructor throws FileNotFoundException.
  2. FileWriter constructor throws FileNotFoundException.
  3. read() method throws IOException.
  4. write() method throws IOException.
  5. Both close() methods throw IOException.

Note: For more clear explanation, it is advised to read FileToFile1.java program before this.

Leave a Reply

Your email address will not be published. Required fields are marked *