Advanced Java Programming - Old Questions
5. Write a simple java program that reads data from one file and writes the data to another file (5)
Let us suppose we have a file named “test.txt” in D-drive. Now we first read from this file character-by-character and later we write the contents of this file to another file say “testwrite.txt” in E-drive. For these tasks, we use the character stream classes namely FileReader and FileWriter. The code is given below:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWrite {
public static void main(String []args) {
try
{
FileReader fr = new FileReader("D:\\\\test.txt");
FileWriter fw = new FileWriter("E:\\\\testwrite.txt");
int c;
while((c=fr.read())!=-1) {
fw.write(c);
System.out.print((char)c);
}
fr.close();
fw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}