AI Hints
Home›Java Tutorial›Writing Files, Reading Files, Practice: Save and Load
Java · Lesson 97 of 120

Writing Files

Save data to disk.

⏱ 2 min read▶ Video at 2:03:01🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

When a program ends, its variables disappear. To keep data for next time, you save it to a file. Java's Files class makes this easy.

  • Variables disappear
  • Files remain
  • The Files class

Writing text

Path dot of names a file. Files dot write string writes text to it, creating the file, or replacing it. With the append option, it adds to the end instead. Files dot write takes a list, and writes one line for each item. Exists, and size, check the result. Run it. The file exists, and holds eighteen bytes.

Main.javajava
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class Main {
    public static void main(String[] args) throws IOException {
        Path notes = Path.of("notes.txt");
        Files.writeString(notes, "Buy milk\n");
        Files.writeString(notes, "Call Sam\n", StandardOpenOption.APPEND);
        Files.write(Path.of("colours.txt"), List.of("red", "green", "blue"));
        System.out.println("notes.txt exists? " + Files.exists(notes));
        System.out.println("Size: " + Files.size(notes) + " bytes");
    }
}
Output
notes.txt exists? true
Size: 18 bytes

Writing options

Write string replaces a file's contents. Add standard open option dot append, to add to the end. Writing can fail, so these methods throw IO exception. Here, main just declares it, with throws.

keyvalue
writeString(p, s)replace contents
…, APPENDadd to the end
write(p, list)one line per item
Can failthrows IOException

Summary

Files dot write string, and Files dot write, save text to a file. Use append to add to the end. Next, reading it back.

Key takeaways
  • Path.of("x.txt")
  • Files.writeString
  • APPEND
Next up: Reading Files — load data from disk