Created: 2023-08-28 15:14
Status: #concept
Subject: Programming
Tags: Java Java Package java.util.Scanner Java Exception

java.nio.file

Defines interfaces and classes for the Java Virtual Machine to access Java File, file attributes, and Filesystems.

  • when we have a Path object, we can read from it using a new Scanner(Path file).

Reading a File with java.nio.file.Paths

The path to the file can be acquired using Java's Paths.get command, which is given the file's name in string format as a parameter.

 Paths.get("filename.extension");

// first
import java.util.Scanner;
import java.nio.file.Paths;

// in the program:

// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.txt"))) {

    // we read the file until all lines have been read
    while (scanner.hasNextLine()) {
        // we read one line
        String line = scanner.nextLine();

		// if the line is blank we do nothing
        if (line.isEmpty()) {
            continue;
        }

        // we print the line that we read
        System.out.println(line);
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}
A file is read from the project root by default (when new Scanner(Paths.get("file.txt")) is called).

  • This is the folder that contains the folder src and the file pom.xml.
  • The contents of this folder can the inspected using the Files-tab in NetBeans.

Reading File Contents as a Java Stream

We can use the Files.lines(Paths.get("file.txt")) to return a Stream<E> of every line in the file which we can manipulate.

List<String> rows = new ArrayList<>();

try {
    Files.lines(Paths.get("file.txt")).forEach(row -> rows.add(row));
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
    // Error: file.txt (No such file or directory)
}

// do something with the read lines

Writing to Files with java.io.PrintWriter

Just like how we can read a file with new Scanner(Paths.get(file)), we an make a writable file with new PrintWriter(file).

  • .println(String) prints a line with \n, overwriting the file if it already exists.
  • .close() closes the stream, NEEDED.

public class Storer {

    public void writeToFile(String fileName, String text) throws Exception {
        PrintWriter writer = new PrintWriter(fileName);
        writer.println(text);
        writer.close();
    }
}

Appending to Files with java.io.FileWriter

To append data to an existing file or create a new file if it doesn't exist, you can set the second parameter of type boolean, which specifies whether the file should be opened in append mode (true) or overwrite mode (false).

  • It is similar to PrintWriter, but we use .write() instead to append new lines to the file.

try (FileWriter writer = new FileWriter("output.txt", true)) {
    // This will append to the file or create a new one if it doesn't exist
    writer.write("Appending some data.\n");
} catch (IOException e) {
    e.printStackTrace();
}

References