< Prev
Next >



FileReader



FileReader class is a subclass of Reader abstract class and it is used to read a character/characters from a local file.




Constructor :


FileReader(File file)
This constructor creates a FileReader object to read out the contents of a file referenced by a File object.
Example-:
File file = new File("D:\\Textbook.txt");
FileReader fr = new FileReader(file);





Methods for reading FileReader


Some methods that we generally use while working with FileReader are shown in the table below :

Methods Description
available()
This method gives the remaining number of bytes available to read from this input stream.

read()
This method reads one character at a time from this input character stream.

read(char[])
This method reads a whole character array at a time from this input character stream.

close()
This method closes this input stream and also frees any resources connected with this input stream.






Reading one character a time from a file using FileReader class.


We are reading an existing file called TextBook.txt using its path D:\\TextBook.txt. Let's say the contents of this file are -
Hello there!
FileReader class is a subclass of Reader class.

import java.io.*;
class A
{
public static void main(String... ar)
{

try
{
File file= new File("D:\\TextBook.txt");
FileReader fr= new FileReader(file);
int c;

//Reading one character a time from a file until -1 is returned
while( (c=fr.read())!=-1)
{
System.out.print((char)c);
}

fr.close();
}
catch(IOException e)
{
System.out.println(e);
}

}
}



Output is -:


Hello there!
FileReader class is a subclass of Reader class.


Program Analysis





Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< CharArrayWriter
FileWriter>
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2