Here is a compact way to read file line by line using the java.util.Scanner
class.
package org.kodejava.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
// Create an instance of File for data.txt file.
File file = new File("README.md");
try {
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it, we call the scanner.hasNextLine()
// method. We then read line one by one till all lines
// is read.
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024