CodeBlanks Logo Icon CodeBlanks

File I/O

Save and load data as JSON.

Writing to a file with Files.write

To make orders persistent you write them to a file. Java's java.nio.file.Files class makes this easy. The call Files.write(Path.of("orders.txt"), lines) writes a List<String> to a file; each element becomes a line.

To read back, use Files.readAllLines(Path.of("orders.txt")); this method returns the file lines as a List<String>. Both methods can throw IOException; therefore the main signature adds throws IOException.

IOException and throws

File operations can throw IOException; it is a checked exception. The compiler requires either try/catch handling or adding throws IOException to the method signature. In the project the shortest path is public static void main(String[] args) throws IOException.

The Path.of("orders.txt") call builds a relative path; the file appears in the working directory. Files.write creates the file if absent, or overwrites if present. Files.readAllLines throws NoSuchFileException if the file is missing.

Practice Add the save and load methods

Add save and load methods to the OrderBook class. The void save(String path) throws IOException method: build lines with orders.stream().map(o -> o.id + "|" + o.customer + "|" + o.amount).collect(Collectors.toList()) and write with Files.write(Path.of(path), lines). The int load(String path) throws IOException method: return Files.readAllLines(Path.of(path)).size();. Add throws IOException to the main signature. In main, add two orders, call book.save("orders.txt");, then print the line count with System.out.println(book.load("orders.txt"));.

Starter code

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

class Order {
    String id;
    String customer;
    int amount;
    Order(String id, String customer, int amount) {
        this.id = id;
        this.customer = customer;
        this.amount = amount;
    }
}

class OrderBook {
    List<Order> orders = new ArrayList<>();
    void add(Order o) { orders.add(o); }
    void listAll() {
        orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));
    }
    List<Order> largeOrders() {
        return orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList());
    }
}

// Add save and load methods to OrderBook (throws IOException)

// main: add throws IOException, add two orders, call save and load, print count

Sample solution

Main.java
class Order {
    String id;
    String customer;
    int amount;
    Order(String id, String customer, int amount) {
        this.id = id;
        this.customer = customer;
        this.amount = amount;
    }
}

class OrderBook {
    List<Order> orders = new ArrayList<>();
    void add(Order o) { orders.add(o); }
    void listAll() {
        orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));
    }
    List<Order> largeOrders() {
        return orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList());
    }
    void save(String path) throws IOException {
        List<String> lines = orders.stream()
            .map(o -> o.id + "|" + o.customer + "|" + o.amount)
            .collect(Collectors.toList());
        Files.write(Path.of(path), lines);
    }
    int load(String path) throws IOException {
        return Files.readAllLines(Path.of(path)).size();
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        OrderBook book = new OrderBook();
        book.add(new Order("1", "Ayşe", 50));
        book.add(new Order("2", "Alex", 150));
        book.save("orders.txt");
        System.out.println(book.load("orders.txt"));
    }
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the Files.write call

Question
Files.____(Path.of("orders.txt"), lines);
Answer
Files.write(Path.of("orders.txt"), lines);

Explanation: Files.write writes a List<String> to a file.

2 Match the file I/O concepts

Term Meaning
Files.write Writes List<String>
Files.readAllLines Reads List<String>
Path.of Builds a path
throws IOException Declares exception

3 What does Files.readAllLines return?

  • List<String> Correct answer
  • An int
  • void
  • A String

Explanation: Files.readAllLines returns the file lines as a List<String>.

All lessons in Intermediate