Skip to content

Files (course memo)

Java, java.nio.file (Path, Files).

Reading files

Two steps: finding the file, reading it. Path and Files handle those. If anything goes wrong, an exception is thrown.

Finding: know the file's path relative to the project root (in IntelliJ, usually starting with src/...). Path.of(file) returns a Path object pointing at it.

java
String file = "src/academy/everyonecodes/doc.txt";
Path path = Path.of(file);

Reading: either handle the exception with try/catch, or propagate it with throws on the method.

java
String file = "src/academy/everyonecodes/doc.txt";
Path path = Path.of(file);
try {
    List<String> lines = Files.readAllLines(path);
} catch (IOException e) {
    e.printStackTrace();
    // TODO: Handle error
}

// Or, propagating instead:
public List<String> read() throws IOException {
    String filePathAsString = "src/io/everyonecodes/doc.txt";
    Path path = Path.of(filePathAsString);
    return Files.readAllLines(path);
}

Files.readAllLines (and most file operations) can throw IOException (input/output exception) — either catch it or declare throws to propagate it down the call stack.

Writing files

Same two-step shape: specify the file, then write it.

java
String file = "src/academy/everyonecodes/doc.txt";
Path path = Path.of(file);
List<String> lines = List.of("Line 1", "Line 2");
try {
    Files.write(path, lines);
} catch (IOException e) {
    e.printStackTrace();
    // TODO: Handle error
}

// Or, propagating instead:
public List<String> write() throws IOException {
    String filePathAsString = "src/io/everyonecodes/doc.txt";
    Path path = Path.of(filePathAsString);
    List<String> lines = List.of("Line 1", "Line 2");
    return Files.write(path, lines);
}
  • Path.of(file) creates the file at that path if it doesn't exist yet.
  • Files.write(path, lines) — by default creates the file if missing, or replaces its content entirely if it already exists.
  • Extra options as a third argument:
    java
    Files.write(path, lines, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
    APPEND writes at the end of the existing file instead of replacing it; CREATE creates the file if it doesn't exist yet.
  • Files.exists(path) — check if a file exists (returns boolean).
  • Files.delete(path) — deletes a file, wrapped in try/catch (throws IOException).