C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
While true: We use a while-true loop to continually access the BufferedReader. When readLine returns null, no more data is available.
Line: The readLine method returns a String object. We can use this like any other String object in Java.
Close: Finally we invoke the close method. This is needed to clean up the system resources. Please note an IOException may be thrown.
Java program that uses BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Program {
public static void main(String[] args) throws IOException {
// Create a BufferedReader from a FileReader.
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\file.txt"));
// Loop over lines in the file and print them.
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
// Close the BufferedReader.
reader.close();
}
}
Output
First line.
Second line.
Count lines: This program also counts the lines in a file. It accesses size() on the filled ArrayList.
Java program that uses BufferedReader, ArrayList
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<>();
// New BufferedReader.
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\file.txt"));
// Add all lines from file to ArrayList.
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
list.add(line);
}
// Close it.
reader.close();
// Print size of ArrayList.
System.out.println("Lines: " + list.size());
// Print each line.
for (String line : list) {
System.out.println(line);
}
}
}
Output
Lines: 2
First line.
Second line.
Count: When we call count() on the Stream, the file is read into memory line-by-line and the total count of lines is returned as a long.
Java program that counts lines in file
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Program {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\programs\\file.txt"));
// Count lines in the file.
// ... Call count() on the lines Stream.
long lines = reader.lines().count();
System.out.println("Lines: " + lines);
// Close it.
reader.close();
}
}
Output
Lines: 9