Hard Link Shares File Content Via CreateLink

Create a hard link with Files.createLink so both names share one inode: writes via either path are visible to both and deleting one name keeps the data.

JavaData Integrity

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class HardLinkShare {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("links-");
        Path original = dir.resolve("blob.bin");
        Files.writeString(original, "shared payload");

        // Hard link: a second name for the same inode; no content is copied
        Path alias = dir.resolve("alias.bin");
        Files.createLink(alias, original);

        // A write through either name is instantly visible through the other (one shared content)
        Files.writeString(alias, "rewritten through alias");
        System.out.println("via original: " + Files.readString(original));

        // Deleting the original keeps the data alive: the hard-link reference count is still positive
        Files.delete(original);
        System.out.println("after delete original: " + Files.readString(alias));

        // Contrast: a copy is an independent duplicate; the two names no longer affect each other
        Path copied = dir.resolve("copy.bin");
        Files.writeString(alias, "shared payload");
        Files.copy(alias, copied);
        Files.writeString(alias, "changed after copy");
        System.out.println("copy unaffected: " + Files.readString(copied));
    }
}

How it works

The code’s whole job belongs to the class HardLinkShare.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The run emits 3 labeled sections — via original:, after delete original:, copy unaffected: — one per step.

Key statements

Files.writeString(alias, "rewritten through alias");
Path dir = Files.createTempDirectory("links-");
Files.writeString(alias, "changed after copy");

Interactive Tools for This Topic

FAQ

What does Hard Link Shares File Content Via CreateLink print when run?
No setup needed: run the file and look for labeled lines like `via original:`, `after delete original:`, `copy unaffected:` in the output.