-
Notifications
You must be signed in to change notification settings - Fork 4
Java Reading text files with Scanner
Ramesh Fadatare edited this page Jul 11, 2019
·
1 revision
A Scanner is simple text scanner which can parse primitive types and strings using regular expressions.
The example reads a text file using a Scanner.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadTextFileEx4 {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "src/resources/thermopylae.txt";
Scanner scan = null;
try {
scan = new Scanner(new File(fileName));
StringBuilder sb = new StringBuilder();
while (scan.hasNext()) {
String line = scan.nextLine();
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
} finally {
if (scan != null) {
scan.close();
}
}
}
}
The file is read line by line with the nextLine() method:
while (scan.hasNext()) {
String line = scan.nextLine();
sb.append(line);
sb.append(System.lineSeparator());
}