Read Symbolic Link Target Path

Create a symlink and read back the raw target stored inside it with Files.readSymbolicLink, keeping toRealPath as the follow-the-link view of the same path.

JavaData Integrity

Code

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

public class LinkTarget {

    public static void main(String[] args) throws IOException {
        Path real = Files.createTempFile("target-", ".txt");
        Files.writeString(real, "production config");
        Path link = real.resolveSibling("latest.txt");

        try {
            Files.createSymbolicLink(link, real);
        } catch (IOException | UnsupportedOperationException denied) {
            // Windows 未开开发者模式/无特权时建软链会失败:如实退出,不假装成功
            System.out.println("symlink creation unavailable: "
                    + denied.getClass().getSimpleName());
            Files.deleteIfExists(real);
            return;
        }

        // readSymbolicLink 返回链接本身存储的原始目标(可能仍是相对路径)
        Path storedTarget = Files.readSymbolicLink(link);
        System.out.println("stored target: " + storedTarget);
        System.out.println("is symbolic: " + Files.isSymbolicLink(link));
        // toRealPath 跟随软链,落到真实文件——与 storedTarget 是两个视角
        System.out.println("resolved: " + link.toRealPath().getFileName());
        System.out.println("content via link: " + Files.readString(link));

        Files.deleteIfExists(link);
        Files.deleteIfExists(real);
    }
}

Behavior at a glance

Everything happens inside the class LinkTarget.

Points of care

  • The stock toolchain runs it — nothing extra required.

Putting it to use

The file’s steps show up in the output as symlink creation unavailable:, stored target:, is symbolic:.

Core lines

Path real = Files.createTempFile("target-", ".txt");
Path storedTarget = Files.readSymbolicLink(link);
Path link = real.resolveSibling("latest.txt");

Interactive Tools for This Topic

FAQ

What does Read Symbolic Link Target Path print when run?
Run it as a complete program — the output lines carry labels such as `symlink creation unavailable:`, `stored target:`, `is symbolic:`.