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.
Code
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
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Markdown Link ExtractorExtract inline and reference-style links from Markdown with titles and definitions resolved into a plain list.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.