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
public class FRFWFileCopy
public static void main(String args)
FileReader fr = new FileReader("pqr.txt");
FileWriter fw = new FileWriter("xyz.txt");
while( ( k = fr.read() ) != -1 )
System.out.println("File does not exist. " + e);
System.out.println("Some I/O problem. " + e);
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()
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".
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.
- FileReader constructor throws FileNotFoundException.
- FileWriter constructor throws FileNotFoundException.
- read() method throws IOException.
- write() method throws IOException.
- Both close() methods throw IOException.
Note: For more clear explanation, it is advised to read FileToFile1.java program before this.