listFiles() of File not working on symbolic links?

前端 未结 4 1879
南旧
南旧 2021-02-08 01:51

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

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


        
相关标签:
4条回答
  • 2021-02-08 02:18

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

    0 讨论(0)
  • 2021-02-08 02:20

    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.

    0 讨论(0)
  • 2021-02-08 02:24

    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();
    
    0 讨论(0)
  • 2021-02-08 02:37

    You could read the Symbolic LINK

    0 讨论(0)
提交回复
热议问题