← Back to Core Java Course | Chapter 12: File I/O | Lesson 9 of 9

Java NIO & Path

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?

java
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);
	}
}

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

java
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());
	}
}

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

java
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());
	}
}

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

java
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);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.