JavaFile processing

Reading files

The standard Java class library provides several ways to read data from files. Some of them are quite old, others have appeared recently. In this topic, we will consider only a few simple methods. You can choose the one that is most suitable for you.

Reading data using Scanner

It is possible to use java.util.Scanner to read data from files. First, we should create an instance of java.io.File, and then an instance of Scanner passing the file object. After we can get data from the file using the scanner in the same way as we read from the standard input.

Suppose, you have a string called pathToFile. It keeps the path to a file which contains a sequence of numbers separated by spaces.
Let's create a file object and then a scanner to read data from the file.

File file = new File(pathToFile);
Scanner scanner = new Scanner(file); // it throws FileNotFoundException (checked)

When you create an instance of Scanner passing a file, you must handle the checked exception FileNotFoundException. You can also declare the method as throwing this exception.

Now, we can use methods of Scanner to read data as strings, integers and so on.

Let's read all integers from the file:

while (scanner.hasNextInt()) {
    System.out.print(scanner.nextInt() + " ");
}

This code reads each number from the file and outputs it to the standard output.

After using a scanner, we should close the object to avoid leaks. A convenient way to close scanners and handle exceptions is to use the try-with-resources statement as below.

File file = new File(pathToFile);

try (Scanner scanner = new Scanner(file)) {
    while (scanner.hasNextInt()) {
        System.out.print(scanner.nextInt() + " ");
    }
} catch (FileNotFoundException e) {
    System.out.println("No file found: " + pathToFile);
}

The scanner also allows you to read strings, lines, boolean, doubles and other types. Instead of displaying the read data to the standard output, you can store them in an array or a string.

Reading all text from a file as a single string

Since Java 1.7 there is a set of new classes and methods for handling files. We will not consider them in details, just see how to read an entire text file.

First, make the following imports:

import java.nio.file.Files;
import java.nio.file.Paths;

The Files class consists of methods that operate on files, the Paths class contains a set of methods which returns a special object to represent the path to a file.

The following method returns all text from a specified file.

public static String readFileAsString(String fileName) throws IOException {

    return new String(Files.readAllBytes(Paths.get(fileName)));
}

Let's try to use the method readFileAsString to read source code from the file HelloWorld.java and print it to the standard output.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadingFileDemo {

    public static String readFileAsString(String fileName) throws IOException {

        return new String(Files.readAllBytes(Paths.get(fileName)));
    }

    public static void main(String[] args) {

        String pathToHelloWorldJava = "/home/username/Projects/hello-world/HelloWorld.java";

        try {
            System.out.println(readFileAsString(pathToHelloWorldJava));
        } catch (IOException e) {
            System.out.println("Cannot read file: " + e.getMessage());
        }
    }
}

It prints the source code:

package org.hyperskill;

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, world!");
    }
}

Note, it is not difficult to modify the code above to read the path to the target file from the standard input instead of hardcoding it.
3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo