2

I need to get a list of all files that exist in a directory including broken symlinks and other entries that would be considered invalid by File.listFiles().

I tried multiple different ways of listing files in Java and all of them seem to discard "invalid" files.

To reproduce this issue:

# Create a symlink to a nonexistent path
ln -s /nonexistent/path $PWD/broken_link

# Create a valid symlink
ln -s /path/to/existing/file $PWD/working_link

# Create a normal file
touch empty_file
var files = new File(".").listFiles();

Arrays.stream(files).forEach(file -> {
  System.out.println(file.getName();
});

Expected output (in no particular order):

broken_link
working_link
empty_file

Actual output:

working_link
empty_file

Considering the nature of Java, a multiplatform solution would be ideal but reallistically I only need this to work on POSIX systems (namely macOS and Linux) but I would like to avoid any kind of external dependencies (such as parsing th eoutput of ls, using JNI, etc).

Jake S.
  • 568
  • 6
  • 25
  • 1
    In other words, what is an "invalid" file? How can I create one to reproduce? I'm afraid if the standard ways do not work out of the box, you will eventually need to do one of the other solutions you want to avoid, like parsing `ls`. – Petr Janeček Jan 23 '23 at 17:31
  • For dealing with symlinks, see: [Resolving Directory Symlink in Java](https://stackoverflow.com/questions/28371993), [How to read a symlink file in Java?](https://stackoverflow.com/questions/75086985). – hc_dev Jan 23 '23 at 18:08
  • 2
    The issue cannot be reproduced on linux 5.10.74-gentoo with openjdk version "1.8.0_332", see https://pastebin.com/xDmkDczH. Please [edit] your question to include the version numbers you have on your system. – Progman Jan 23 '23 at 19:31
  • What does `File.list()` give you? – David Jones Jan 23 '23 at 19:35
  • 3
    Cannot reproduce with openjdk 17.0.5 on Ubuntu 22.04.1 LTS. Both `new File(".").listFiles()` and `Files.list()` show all three files (broken, working and empty). – Petr Janeček Jan 23 '23 at 21:38

0 Answers0