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?
You can't. Unfortunately the API doesn't provide you with a way to find out about the underlying I/O error.
File.listFiles()
requires null
check on return value - should have better error handling
The various
listFiles
methods ofFile
all have the following annoying feature: they may possibly returnnull
if an I/O error occurs.This behavior is very inconvenient, because it means that not only must I have code that handles
IOException
s (which is fine), but I also have to do additionalnull
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 timesthrow Exception
s!Evaluation: We plan to address this longstanding problem in the forthcoming new filesystem API.
Use java.nio.file.DirectoryStream
(in Java 7+) and you will get proper exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With