In Java, Files.createLink(link, existing) creates a hard link: a new name, link, for the data of an existing file. Both names are equal; neither is "the original". Changes through one name are visible through the other.
The data stays on disk until the last name is deleted. Hard links work for regular files on the same drive or volume, on NTFS (Windows) and on typical macOS and Linux file systems. Note the argument order: the new name comes first.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.createLink(...), after import java.nio.file.Files;. You never create a Files object.
Syntax
New link name first, existing file second:
Java
Path original = dir.resolve("original.txt");
Path alias = Files.createLink(dir.resolve("alias.txt"), original);
// alias.txt and original.txt now share the same data
Call
What it does
Files.createLink(link, existing)
Adds the name link for the file existing.
Files.isSameFile(link, existing)
true: both names lead to one file.
Files.getAttribute(p, "unix:nlink")
Number of names a file has (Linux/macOS only).
Since Java 7. A hard link is not a shortcut: there is no "target" to read back, and isSymbolicLink returns false. For a pointer to another path, use createSymbolicLink.
Library declarations
Java
public static Path createLink(Path link, Path existing) throws IOException
Run with java CreateLinkCount. The first part is the Linux/macOS output; the last part shows Windows.
Name taken: FileAlreadyExistsException
Link count: 2
--- On Windows ---
Name taken: FileAlreadyExistsException
Link count: no unix attribute view here
How It Works
Existing names are protected. data-link.bin already exists, so a second createLink with that name throws FileAlreadyExistsException on every system.
The link count. On Linux and macOS the attribute unix:nlink is an Integer with the number of names, 2 here.
No unix view on Windows. Asking for an attribute view the platform does not have throws UnsupportedOperationException, so the program prints a fallback line.
Frequently Asked Questions
A second directory entry for the same file data, created with Files.createLink(newName, existing). Both names are equal, and the data is removed only when the last name is deleted.
A hard link is another name for the same data on the same drive and cannot dangle. A symbolic link stores a path to the target, can point to folders or other drives, can dangle, and needs extra privileges on Windows.
Yes, on NTFS drives, without administrator rights. FAT and exFAT drives do not support hard links.
Generally no. Windows, Linux, and macOS normally refuse hard links to folders, and the call throws an IOException.
On Linux and macOS read Files.getAttribute(path, "unix:nlink"), which returns an Integer. Windows has no unix view, so that call throws UnsupportedOperationException.