Java FileReader Example

The ReadFile example reads a file, File1.txt, and prints out the contents of the file to the standard output stream using the System.out.print method.

ReadFile

import java.io.*;

public class ReadFile
{

public static void main(String[] args) throws
IOException
{
File inputFile = new File(''File1.txt");
if ( ! inputFile.exists() )
{
System.out.println("File does not exist");
System.exit(1);
}

FileReader in = new FileReader(inputFile);
int c;
while ((c = in.read()) != -1)
{
System.out.print( (char) c );
}
in.close();
}
}



In line 7, we create a file object, inputFile, using the java.io.File constructor. In line 8, we test the physical existence of this file using the java.io.File.exists method. If the file does not exist, the program prints a message, then terminates using the System.exit method (lines 9–10).

If the file does exist, we then create an input stream, in, with the java.io.FileReader constructor (line 12). In line 14, we use the java.io.FileReader.read method to read a single character from the input stream. This method returns a value of –1 when the end of the input stream is reached. Consequently, the while statement will read all the characters in turn from the input stream. The read method returns a character, c, of type int, so we need to cast this to a char type to use the System.out.print method in line 15.

Analogous to FileWriter, FileReader is actually a convenience class that is equivalent to an InputStreamReader stream wrapped around a FileInputStream.

No comments:

Post a Comment