Question
Given a Java 'File' object, how can I detect whether or not it refers to a symlink? Then resolve its real absolute path.
How-To
File.getCanonicalPath() resolves symlinks:
From JDK8+, you can leverage Files.isSymbolicLink(Path path) to check the give path is symbolic or not.
The technique used in Apache Commons uses the canonical path to the parent directory, not the file itself. I don't think that you can guarantee that a mismatch is due to a symbolic link, but it's a good indication that the file needs special treatment.
This is Apache code (subject to their license), modified for compactness:
- public static boolean isSymlink(File file) throws IOException {
- if (file == null)
- throw new NullPointerException("File must not be null");
- File canon;
- if (file.getParent() == null) {
- canon = file;
- } else {
- File canonDir = file.getParentFile().getCanonicalFile();
- canon = new File(canonDir, file.getName());
- }
- return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
- }
Then below is the testing groovy code:
- test.groovy
- #!/usr/bin/env groovy
- import java.nio.file.attribute.BasicFileAttributes
- import java.nio.file.attribute.PosixFileAttributes;
- import java.nio.file.Files
- import java.nio.file.Path;
- import java.nio.file.Paths;
- public static boolean IsSymlink(File file) throws IOException {
- if (file == null)
- throw new NullPointerException("File must not be null");
- File canon;
- if (file.getParent() == null) {
- canon = file;
- } else {
- File canonDir = file.getParentFile().getCanonicalFile();
- canon = new File(canonDir, file.getName());
- }
- return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
- }
- files = ["cache", "myfile.txt"]
- for(fileName in files)
- {
- File file = new File(fileName)
- printf("AbsolutePath: %s\n", file.getAbsolutePath())
- printf("CanonicalPath: %s\n", file.getCanonicalPath())
- //printf("Path: %s\n", cache.toPath())
- //PosixFileAttributes attrs = Files.readAttributes(file.toPath(), PosixFileAttributes.class);
- printf("Is Symbpolic? %s\n", IsSymlink(file))
- printf("==========================================\n")
- }
Supplement
* Using PosixFileAttributes : File Attribute
沒有留言:
張貼留言