Files is Same File Symlink Identity
Resolve whether two paths denote one file with Files.isSameFile: it follows symlinks, so a link and its target compare equal while copies do not.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class IdentityCheck {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("identity-");
Path target = dir.resolve("report.txt");
Files.writeString(target, "confidential body");
// 同一文件的两个路径:直接相等
Path viaResolve = dir.resolve("report.txt");
System.out.println("same path object = " + Files.isSameFile(target, viaResolve));
// 副本不是同一文件:内容一样也算不同
Path copy = dir.resolve("report-copy.txt");
Files.copy(target, copy);
System.out.println("target vs copy = " + Files.isSameFile(target, copy));
// 符号链接解析后与目标等价(平台不支持时诚实降级)
try {
Path link = dir.resolve("report-link.txt");
Files.createSymbolicLink(link, target);
System.out.println("target vs symlink = " + Files.isSameFile(target, link));
} catch (UnsupportedOperationException | IOException unsupported) {
System.out.println("symlinks unavailable here: " + unsupported.getClass().getSimpleName());
}
}
}How it works
Count the class IdentityCheck as the entire surface area of Files is Same File Symlink Identity.
Using it
The demo output is labeled (same path object =, target vs copy =, target vs symlink =), so every printed line maps back to its originating operation.
Key statements
Path dir = Files.createTempDirectory("identity-");
Files.writeString(target, "confidential body");
Path viaResolve = dir.resolve("report.txt");
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does Files is Same File Symlink Identity print when run?
- The script runs standalone; its 4 labeled outputs include `same path object =`, `target vs copy =`, `target vs symlink =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.