listFiles() of File not working on symbolic links?

天大地大妈咪最大 提交于 2019-12-03 06:11:54

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();

You could read the Symbolic LINK

..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().

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!