Java Files hard and symbolic links
Give a file another directory entry or create a symbolic link that stores a target path.
A simple example
Files hard and symbolic links
- Start with Link named alias points to a.txt
- Do this Read the symbolic link target
- Result a.txt
Syntax
public static Path createLink(Path link, Path existing) throws IOException
JDK 21 declarations (4)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPoint today's timetable at the master copy
A station maintains a master timetable and wants two local names for it. On a disk supporting both link types, compare a hard link with a symbolic shortcut and inspect the name stored inside the shortcut.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path master = Files.writeString(desk.resolve("master.txt"), "09:00");
Path second = Files.createLink(desk.resolve("platform.txt"), master);
Path shortcut = Files.createSymbolicLink(desk.resolve("today"), master.getFileName());
System.out.println(Files.isSameFile(master, second));
System.out.println(Files.isSymbolicLink(shortcut));
System.out.println(Files.readSymbolicLink(shortcut));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true true master.txt
The hard link names the same file. The symbolic link stores a relative pathname that resolves beside it.
Identify a broken timetable shortcut
A timetable update removes its old target while a symbolic shortcut remains. Check the shortcut itself separately from its destination so the display can explain why following it fails.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path link = Files.createSymbolicLink(desk.resolve("today"), Path.of("old.txt"));
System.out.println(Files.exists(link));
System.out.println(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
false true
Following the link finds no target. The no-follow option detects the directory entry for the link.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. A desk makes a symbolic link named latest to the saved note. When a reader follows the link, which contents does it see?
What to watch for
Links require provider support and suitable permissions. A relative symbolic target is resolved from the link's parent.