Java Reading text files with Scanner

A Scanner is simple text scanner which can parse primitive types and strings using regular expressions.

Java Reading text files with Scanner

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());
}



Comments