typestar

Files in Java

Whole-file reads and writes in single calls.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

var path = Path.of(System.getProperty("java.io.tmpdir"), "notes.txt");

Files.writeString(path, "first line\nsecond line\n");
Files.writeString(path, "third line\n", StandardOpenOption.APPEND);

for (var line : Files.readAllLines(path)) {
    System.out.println("> " + line);
}
System.out.println(Files.exists(path));
Files.delete(path);

How it works

  1. Files.writeString creates; the APPEND option extends.
  2. readAllLines hands the file back as a list of strings.
  3. Path.of builds paths without hardcoding separators.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
430
Tokens
110
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 2 of 3 in Errors & files, step 26 of 29 in Language basics.

← Previous Next →

Files in other languages