FileReader in java
In previous post, we have seen FileWriter. In this post, we will see how to read data from a text file with the help of FileReader in java.
FileReader is a character based classe unlike FileInputStream which is used for reading byte based data.In other words, we should use FileReader class when the data is in textual form.
Let’s understand it with example.
FileReader:
It reads data as a stream of characters from a file.
Constructor of FileReader:
Constrctor | Description | |
FileReader(String file) | Filename is passed as String. File is opened in read mode and if file does not exist ,throws FileNotFoundException. | |
FileReader(File file) |
|
Example of FileReader:
import java.io.FileReader; public class FileReaderEx { public static void main(String[] args){ FileReader freader; try { freader = new FileReader("Sample.txt"); int i; while((i=freader.read())!=-1) System.out.println((char)i); freader.close(); } catch (Exception e) { e.printStackTrace(); } } }
FileReader methods:
- public int read() : It returns a character in ASCII form and returns -1 at the end of file.
- public void close() : It closes FileReader.
In next post, we will see FileInputStream and FileOutputStream.
2 Responses
[…] the next post, we will see FileReader which is used for reading data from a text […]
[…] the previous post, We have seen FileReader which is used to read the data from text file. In this post, we will look at FileInputStream and […]