Chapter 5 · Real programs

Files

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 19 · Concept

Files outlive your program

Your variables live in memory. When the program ends, its memory is cleared (lesson 2). A file lives in storage, and stays.

In this lesson you will:

  • write text into a file and read it back,
  • read a file line by line,
  • turn a file of data into a report.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Notes {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("notes.txt");
        Files.writeString(file, "Buy milk\nCall Ada\n");

        String text = Files.readString(file);
        System.out.print(text);

        boolean found = Files.exists(file);
        boolean other = Files.exists(Path.of("missing.txt"));
        System.out.println("notes.txt exists: " + found);
        System.out.println("missing.txt exists: " + other);
    }
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Todo {
    static void save(List<String> items, Path file)
            throws IOException {
    }

    public static void main(String[] args) throws IOException {
        Path file = Path.of("todo.txt");
        Files.deleteIfExists(file);
        List<String> items =
                List.of("Buy milk", "Call Ada", "Learn Java");
        save(items, file);
        if (Files.exists(file)) {
            System.out.print(Files.readString(file));
        } else {
            System.out.println("There is no todo.txt");
        }
    }
}
public class Split {
    public static void main(String[] args) {
        String[] words = "and Java runs".split(" ");
        System.out.println(words.length);
        System.out.println(words[1]);
        String[] parts = "Ada,92".split(",");
        System.out.println(parts[0] + " has " + parts[1]);
    }
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Poem {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("poem.txt");
        List<String> lines = Files.readAllLines(file);
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            String[] words = line.split(" ");
            System.out.printf("%d: %s (%d words)%n",
                    i + 1, line, words.length);
        }
        System.out.println("Lines: " + lines.size());
    }
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Poem {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("poem.txt");
        List<String> lines = Files.readAllLines(file);
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            String[] words = line.split(" ");
            System.out.printf("%d: %s (%d words)%n",
                    i + 1, line, words.length);
        }
        System.out.println("Lines: " + lines.size());
    }
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class WordCount {
    static int countWords(List<String> lines) {
        return 0;
    }

    static String longest(List<String> lines) {
        return "";
    }

    public static void main(String[] args) throws IOException {
        Path file = Path.of("story.txt");
        List<String> lines = Files.readAllLines(file);
        System.out.println("Lines: " + lines.size());
        System.out.println("Words: " + countWords(lines));
        System.out.println("Longest: " + longest(lines));
    }
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;

public class Grades {
    // each line as name and score, in a TreeMap;
    // a score that is not a number: print
    // "Skipped: " and the line, and leave it out
    static Map<String, Integer> load(Path file)
            throws IOException {
        return new TreeMap<>();
    }

    // one line per student: name, score, and
    // "pass" for 50 or more, else "fail";
    // last, the average with two decimals
    static String report(Map<String, Integer> grades) {
        return "";
    }

    public static void main(String[] args) throws IOException {
        Path data = Path.of("grades.txt");
        Map<String, Integer> grades = load(data);
        Path out = Path.of("report.txt");
        Files.writeString(out, report(grades));
        System.out.print(Files.readString(out));
    }
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class SortFile {
    public static void main(String[] args) throws IOException {
        Path out = Path.of("sorted.txt");
        Files.deleteIfExists(out);
        Path source = Path.of("names.txt");
        List<String> names = Files.readAllLines(source);
        // sort names, then write them into out

        if (Files.exists(out)) {
            System.out.print(Files.readString(out));
        } else {
            System.out.println("There is no sorted.txt");
        }
    }
}
Terminal
Step 1 of 8Write a file and read it back

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)