readLine(): This method is available in the java.io.BufferedReader class of Java.
Syntax:
String java.io.BufferedReader.readLine() throws IOException
This method reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), a carriage return followed immediately by a line feed, or by reaching the end-of-file(EOF).
Parameters: NA
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached without reading any characters.
Throws:
IOException - If an I/O error occurs.
Note:
hello.txt contains
Hello World
Approach 1: When no exception
Java
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class BufferedReaderreadLine {public static void main(String[] args) throws IOException {FileReader fileReader = new FileReader("D:\\hello.txt");BufferedReader bufferedReader =new BufferedReader(fileReader);System.out.println(bufferedReader.readLine());bufferedReader.close();}}
Output:
Hello World
Approach 2: IOException
Java
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class BufferedReaderreadLine {public static void main(String[] args) throws IOException {FileReader fileReader = new FileReader("D:\\hello.txt");BufferedReader bufferedReader =new BufferedReader(fileReader);bufferedReader.close();System.out.println(bufferedReader.readLine());}}
Output:
Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedReader.ensureOpen(BufferedReader.java:122) at java.base/java.io.BufferedReader.readLine(BufferedReader.java:319) at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
No comments:
Post a Comment