Java provides java.io.FileReader and java.io.FileWriter classes for reading from and writing characters to a file. The FileReader and FileWri ter classes can be used almost identically to the FileInputStream and FileOutputStream character stream classes.
In order to open a file for reading characters, create a FileReader object. For this, the FileReader class provides the following commonly used constructors,
• FileReader(File fileObj)
• FileReader(String filename)
Here, filename specifies the name of the file and fileObj is a file object that describes the file. If the file to be opened doesnot exist, both these constructors throw java.io.FileNotFoundException.
In order to open a file for writing characters, create a FileWriter object. For this, FileWriter class provides the following commonly used constructors
FileWriter(File file obj)
FileWriter(String filename)
FileWriter(File fileObj, boolean append)
FileWriter(String filename, boolean append)
Here, filename specifies the name of the file and fileObj is a file object that describes the file. If the file doesnot exist, a new file would be created. If the file exists, the first two constructors overwrite the existing contents of the file. To retain the existing contents and append the new data at the end of the file, use the last two constructors and set the second argument append to true.
These constructors throw an IOException on failure.
Now let us consider a program that writes some text into a file and then reads the contents of the file character by character
import java.io.*;
class FileReaderWriter
{
public static void main(String[] args)
{
int ch;
String str="Welcome Java World";
try
{
FileWriter fileWrite = new FileWriter("java.txt");
fileWrite.write(str);
fileWrite.close();
}
catch(IOException e) { e.printStackTrace();}
try
{
FileReader fileRead=new FileReader("java.txt");
while((ch=fileRead.read())!=-1)
System.out.print((char)ch);
fileRead.close();
}
catch(IOException e) { e.printStackTrace();}
}
}