Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the underlying error when File.listFiles return null

Tags:

java

file-io

According to the File.listFiles javadoc the method

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

I know that I am using a directory, but have received a null result, so an I/O error must've appeared. I'm very much interested in what the error was.

How can I retrieve the error message/code when such a null result is returned?

like image 680
Robert Munteanu Avatar asked Jul 12 '10 11:07

Robert Munteanu


2 Answers

You can't. Unfortunately the API doesn't provide you with a way to find out about the underlying I/O error.

See also

  • Bug 4505804: File.listFiles() requires null check on return value - should have better error handling

    The various listFiles methods of File all have the following annoying feature: they may possibly return null if an I/O error occurs.

    This behavior is very inconvenient, because it means that not only must I have code that handles IOExceptions (which is fine), but I also have to do additional null checks on the result.

    Better behavior would be that if an I/O error occurs, then an IOException always gets thrown. You should not use a distinguished return value to sometimes indicate errors, and then also other times throw Exceptions!

    Evaluation: We plan to address this longstanding problem in the forthcoming new filesystem API.

like image 101
polygenelubricants Avatar answered Sep 28 '22 01:09

polygenelubricants


Use java.nio.file.DirectoryStream (in Java 7+) and you will get proper exceptions.

like image 39
Jesse Glick Avatar answered Sep 28 '22 02:09

Jesse Glick