Saturday, November 16, 2013

File Reader Class in Java

This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters. This class has several constructors to create required objects.

Following syntax creates a new FileReader, given the File to read from.
FileReader(File file)

Following syntax creates a new FileReader, given the FileDescriptor to read from.
FileReader(FileDescriptor fd)

Following syntax creates a new FileReader, given the name of the file to read from.
FileReader(String fileName)

Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files.


Example:
Following is the example to demonstrate class:
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}

No comments:

Post a Comment