FileWriter and FileReader class is used to for read and write from a text files. Bothclasses are character-oriented classes in file handling in java. If you working on textual information in the file then, it’s better approach.
FileWriter class:
In Java, FileWriter is a character stream to write data to a file. We used the constructer for creating a file.
For example, we create a file with the help of FileWriter constructor and put the string in the write() method directly.
import java.io.*;
class FileWriterEx{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("FileWriter.txt"); fw.write("My name is khan");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Successfully Done!");
} }
Output:
Successfully Done!
FileReader class:
In Java, FileReader is a character stream to read data from a file.
For example, we working with existing file with the help of FileReader constructor and read the data from its read () method.
import java.io.*;
class FileReaderEx{
public static void main(String args[]){
try{
FileReader fr=new FileReader("FileWriter.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}catch(Exception e){System.out.println(e);} }
}
Output:
My name is khan
Leave Comment