The ‘read()’ method is used to read a single character from an input stream. This method belongs to classes that implement the ‘Reader’ abstract class or its subclasses.
read() method in java
The ‘read()’ method in java reads a single character from an input stream, returning its Unicode value as an integer. If the end of the stream is reached, it returns -1. It is commonly used with classes implementing the ‘Reader’ interface , such as a ‘FileReader’ , to read character data from various sources. Proper error handling for potential ‘IOException’ is necessary, and after usage, it is important to close the stream to release system resources.
Syntax:
int read() throws IOException
parameters:
This method does not take any parameters.
Return Value:
- Returns the character read as an integer in the range 0 to 65535 or -1 if the end of the stream has been reached.
Exceptions:
- ‘IOException’: id an I/O error occurs.
Example:
import java.io.*;
public class ReadFileExample {
public static void main(String args[]){
try{
FileReader f = new FileReader("Example.txt");
int c;
while((c=f.read())!=-1){
System.out.print((char)c);
}
f.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
Output:
If the file “Example.txt” contains the text “Hello, World!”, then the output would be:
Hello, World!