Java BufferedReader readLine() Method
Example
Read the lines of a file, one by one:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Volvo\nBMW");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
System.out.println(br.readLine());
System.out.println(br.readLine());
System.out.println(br.readLine());
br.close();
}
}
Definition and Usage
The readLine() method reads one line of text and returns it as a String. The line break at the end of the line is not included.
When there are no more lines (the end of the file), it returns null. This is why readLine() is often used in a loop: while ((line = br.readLine()) != null).
Tip: A line ends with a line feed (\n), a carriage return (\r), or both (\r\n).
Syntax
public String readLine()
Parameter Values
None.
Technical Details
| Returns: | The line as a String, without the line break, or null if the end of the stream is reached. |
|---|---|
| Throws: | IOException - if the reader is closed, or if another I/O error occurs. |
Related Pages
❮ BufferedReader Methods