listFiles() of File not working on symbolic links?
Asked Answered
B

4

12

I have the following File object pointing to a directory via symbolic link,

File directory = new File("/path/symlink/foo/bar");
String[] files = directory.listFiles();

listFiles() returns null, is this because of the symlink? if yes, how will I go about this if I really want to list the files in bar using the path that contains a symlink?

Boding answered 18/3, 2010 at 16:57 Comment(0)
I
20

According to what I've seen while Googling this puzzling behavior, Java requires that you call .getCanonicalFile() on a File whose path contains a link before you can use it in other file operations.

So:

File directory = new File("/path/symlink/foo/bar").getCanonicalFile();
String[] files = directory.listFiles();
Insincere answered 18/3, 2010 at 17:6 Comment(0)
C
3

You could read the Symbolic LINK

Cupel answered 18/3, 2010 at 17:4 Comment(0)
E
2

..extending what @mickthompson suggested, using the NIO File library (> Java 7) you can:

Path link = Paths.get("/path/symlink/foo/bar");
while (Files.isSymbolicLink(link)) {
    link = Files.readSymbolicLink(link);
}

Path[] files =  Files.list(link).toArray(size -> new Path[size]);

Path is easily converted to File so all your old Java IO code can be safely kept, @see Path#toFile().

Essieessinger answered 26/10, 2016 at 10:40 Comment(1)
Note, that the could be chain of symbolic links. So if would be safer to replace if with while.Sammiesammons
P
0

This is fixed for the 3.0.1 release. After that's released, give it a try and let us know if it's still a problem for you by opening a new bug, linking back to this one for context.

Pretentious answered 16/12, 2017 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.