Java BufferedReader lines() Method
Example
Print all lines of a file with a stream:
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\nFord");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
br.lines().forEach(line -> System.out.println(line));
br.close();
}
}
Definition and Usage
The lines() method returns the lines of text as a Stream<String>. A stream is a sequence of values that you can work with one by one, for example with forEach().
Each line is a String without the line break at the end. The lines are read when the stream is used, so do not close the reader before that.
Tip: The -> in the example is a lambda expression. Learn more in our Java Lambda tutorial.
Syntax
public Stream<String> lines()
Parameter Values
None.
Technical Details
| Returns: | A Stream<String> with the lines of text. |
|---|
Related Pages
❮ BufferedReader Methods