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
Files.writeStringcreates; theAPPENDoption extends.readAllLineshands the file back as a list of strings.Path.ofbuilds paths without hardcoding separators.
Keywords and builtins used here
forvar
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.
Step 2 of 3 in Errors & files, step 26 of 29 in Language basics.