Java NIO & Path
In this page:
What is NIO and Path?
The NIO (New I/O) Path interface represents a filesystem location more flexibly than the older File class, and pairs with the Files utility class for most modern file operations in Java.
Example: What is NIO and Path?
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path path = Path.of("data/notes.txt");
System.out.println(path);
}
}
Login to try C/C++/Java/PHP code in the editor
Extracting Path Information
A Path object lets you extract pieces of a location — getFileName(), getParent(), getRoot() — without manually parsing separator characters yourself.
Example: Extracting Path Information
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path path = Path.of("data/notes.txt");
System.out.println(path.getFileName());
System.out.println(path.getParent());
}
}
Login to try C/C++/Java/PHP code in the editor
Absolute vs Relative Paths
An absolute path fully specifies a location from the filesystem root, while a relative path is interpreted relative to the current working directory — Path.isAbsolute() tells you which kind you're holding.
Example: Absolute vs Relative Paths
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path relative = Path.of("notes.txt");
Path absolute = Path.of("/home/user/notes.txt");
System.out.println(relative.isAbsolute());
System.out.println(absolute.isAbsolute());
}
}
Login to try C/C++/Java/PHP code in the editor
Resolving Paths
resolve() combines a base path with a relative path segment to build a new, longer path, which is the standard NIO way to construct file locations piece by piece.
Example: Resolving Paths
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path base = Path.of("data");
Path full = base.resolve("notes.txt"); // combines pieces
System.out.println(full);
}
}
Login to try C/C++/Java/PHP code in the editor
Normalizing Paths
normalize() cleans up redundant . and .. segments in a path without touching the actual filesystem, giving you a canonical, simplified representation for comparison or display.
Example: Normalizing Paths
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path messy = Path.of("data/../data/./notes.txt");
System.out.println(messy.normalize());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: