English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will understand Java Reader, its subclasses, and its methods through an example.
The Reader class in the java.io package is an abstract superclass that represents character streams.
Since Reader is an abstract class, it does not work by itself. However, its subclasses can be used to read data.
To use the functions of Reader, we can use its subclasses. Some of them are:
In the next tutorial, we will learn about all these subclasses.
To create a Reader, we must first import the java.io.Reader package. After importing the package, we can create a Reader.
// Create Reader Reader input = new FileReader();
Here, we have created a Reader using the FileReader class. This is because Reader is an abstract class. Therefore, we cannot create an object of Reader.
Note:We can also create ReaderReader from other subclasses.
The Reader class provides methods implemented differently by its subclasses. Here are some commonly used methods:
ready(); - Check if the Reader is ready to read
read(char[] array) - Read characters from the stream and store them in the specified array
read(char[] array, int start, int length)- Read a number of characters equal to length from the stream and store them starting from start in the specified array
mark(); - Mark the position of the read data in the stream
reset(); - Reset the stream. If the stream has been marked, then try to mark it again to reposition. If the stream has not been marked, then try to reset it to an appropriate specific stream's methods, such as by relocating it to its starting point.
skip(); -Discard a specified number of characters from the stream
This is how we implement the Reader method using the FileReader class.
Assuming we have a file namedinput.txtThe file contains the following content.
This is a line of text inside the file.
Let's try to read this file using FileReader (a subclass of Reader).
import java.io.Reader; import java.io.FileReader; class Main { public static void main(String[] args) { // Create a character array char[] array = new char[100]; try { //Create a Reader using FileReader Reader input = new FileReader("input.txt"); //Check if the Reader is ready System.out.println("Is there data in the stream? "); + input.ready()); //Read a character input.read(array); System.out.println("The data in the stream:"); System.out.println(array); // Close reader input.close(); } catch(Exception e) { e.getStackTrace(); } } }
Output Result
Is there data in the stream? true Data in the stream: This is a line of text inside the file.
In the above example, we used the FileReader class to create a reader. The Reader is linked to the fileinput.txtLink.
Reader input = new FileReader("input.txt");
In order toinput.txtFile reading data, we have implemented these methods.
input.read(); //Reading data from reader input.close(); //Close reader