Reputation: 21
Folder17
Folder18
Folder19 -> /myfolder/17
Folder20 -> /myfolder/17
I have a created symbolic link from Folder19
to Folder17
and Folder 20
to Folder17
I can use Files.isSymbolicLink(path)
to find whether file is symbolic linked. But is there another way around ? I wanted to know all the folders linked to me. Like, in this case, I want to know all links for Folder17
which should give me Folder19
and Folder20
I created below have something like below cd /foo
mkdir b
ln -s /foo/b e
ln -s /foo/b f
ln -s /foo/b g
ls -la
b
e -> /foo/b
f -> /foo/b
g -> /foo/b
In my java class, I did below.I was expecting to return e,f,g with size 3. But the size is 0
Path path = Paths.get("/foo/b");
Collection<Path> paths = Files.walk(path)
.filter(Files::isSymbolicLink)
.filter(p -> {
try {
return path.equals(Files.readSymbolicLink(p));
} catch (IOException e) {
System.out.println("log");
throw new RuntimeException("An I/O error has occurred!");
}
})
.collect(Collectors.toList());
System.out.println(paths.size());
}
catch(Exception e)
{
e.printStackTrace();
}
}
Upvotes: 2
Views: 539
Reputation: 29700
Good question. You can probably see why it would be redundant for some file A
to track every file that is symbolically-linked to A
, as that could potentially take up a large amount of space. For that reason, it would be simple to navigate through the directory, checking for symbolic links to file A
. You can use something similar to the following:
Files.walk(path)
.filter(Files::isSymbolicLink)
.filter(p -> {
try {
return path.equals(Files.readSymbolicLink(p));
} catch (IOException e) {
throw new RuntimeException("An I/O error has occurred!");
}
})
.collect(Collectors.toList());
This returns a List<Path>
containing all of the Path
s which are symbolic links to path
.
Note: You can use Files#walkFileTree
to recursively search through these directories if needed.
Upvotes: 3