Video in progress

Strong Junior 📁 IO and NIO

A relative path like Path.of("data/input.txt") is resolved relative to which directory?

A relative path is resolved against the current directory the JVM was started from (the working directory, user.dir), not against where the class file or the jar is. That is why code that worked in the IDE can fail to find the file on the server.

📖 Answer

In IntelliJ the working directory is usually the project root. On a server the application is started from a different directory through systemd or Docker, and data/input.txt points somewhere completely different.

Checking is easy:

System.out.println(Path.of("").toAbsolutePath());
System.out.println(System.getProperty("user.dir"));

To see the error in the log, always print the path in its absolute form:

Path p = Path.of("data/input.txt");
log.info("Fayl o'qilmoqda: {}", p.toAbsolutePath());

On prod I don't rely on relative paths. The usual solutions:

  • the path comes from configuration: app.storage.dir=/var/lib/myapp;
  • in Docker, the volume is mounted at an exact location;
  • in a systemd unit, WorkingDirectory= is set.

If you need the user's home directory, use System.getProperty("user.home"). Java doesn't understand ~; that is the shell's job.