Memra

File, Path & the filesystem

The File class, relative vs absolute paths, and the no-hard-coded-path rule.

File names a path, not the bytes

A java.io.File object is an abstract pathname — it represents a *path* in the filesystem, whether or not anything exists there. Creating a File opens nothing and reads nothing; it just holds the name. You then query or act on it:

File f = new File("dump.out");
boolean here   = f.exists();          // does it exist?
long    size   = f.length();          // bytes, or 0 if absent
String  abs    = f.getAbsolutePath(); // resolve against the working dir
boolean gone   = f.delete();          // remove it

Relative vs absolute paths

A path is absolute if it starts from the filesystem root (/home/u/dump.out on Unix, C:\\Users\\u\\dump.out on Windows). A path is relative if it does not — it is then resolved against the process's current working directory (the folder the program was launched from), which you can read with System.getProperty("user.dir").

So new File("dump.out") refers to a file named dump.out *in whatever directory the program runs from*. This is exactly what the Greenhouse project wants: it writes dump.out, error.log, and fix.log into the working directory, with no hard-coded absolute paths.

Why hard-coded paths are a defect

Hard-coding "/home/steve/comp308/dump.out" ties the program to one machine and one user. It breaks the instant the grader runs it from another folder or another OS — and the project rubric penalizes it. The portable habits are:

- Use a relative filename and let the working directory decide location. - Build paths with the separator constant File.separator (or, better, the multi-arg File constructor) rather than a literal / or \\.

// portable: joins with the OS-correct separator
File out = new File("logs", "error.log");   // logs/error.log or logs\\error.log

A note on java.nio.file.Path

Modern Java (Java 7+) adds java.nio.file.Path and Files, a richer API (Paths.get("dump.out"), Files.readAllLines(path), Files.exists(path)). It is the preferred API in new code, but the AU exam and the project are anchored to the classic java.io.File, so know File first and treat Path as the modern equivalent.

NORMAL ~/memra/learn/comp-308/file-and-paths utf-8 LF