×

java · level 2 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Save one record per line, then each line into parts.

A file of books works best with one book per line, like Holes,Louis Sachar,1998. That layout is called , comma-separated values. Files.write(path, lines) saves a list of strings, one per line, and gives them back as a List<String>.

line.split(",") cuts a line into an array wherever a comma appears: parts[0] is the title and parts[2] the year. Every part is text, so use Integer.parseInt when you need a number. Now each line can become data again.

import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("books.csv");
        Files.write(path, List.of("Holes,Louis Sachar,1998", "Matilda,Roald Dahl,1988"));
        List<String> lines = Files.readAllLines(path);
        System.out.println(lines.size() + " books");
        for (String line : lines) {
            String[] parts = line.split(",");
            System.out.println(parts[0] + " (" + parts[2] + ") by " + parts[1]);
        }
    }
}

List<String> works like the lists you know, because ArrayList is one kind of List.