Tsallaka zuwa abun ciki
Justice Tech School

Reading and Writing Files

Files and Path from java.nio.file read and write text in one line each. Use try-with-resources for streams that need closing. File operations can throw IOException, which you must handle or declare.

Example
import java.nio.file.*;
import java.util.List;

public class Main {
  public static void main(String[] args) throws Exception {
    Path file = Files.createTempFile("notes", ".txt");
    Files.writeString(file, "first\nsecond\n");
    List<String> lines = Files.readAllLines(file);
    System.out.println(lines);
    System.out.println(Files.readString(file).length());
    Files.delete(file);
    System.out.println(Files.exists(file));
  }
}

Result

[first, second]
13
false

Exercise

Which exception can file operations throw?

throws 

Quiz Test

Why use try-with-resources?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.