Reputation: 13382
This code
URL listofFiles = this.getClass().getResource("someDir");
File f = new File(listofFiles.toString());
File[] files = f.listFiles();
runs in a JUnit unit test in a Tomcat webserver environment.
The URL that's returned is most definitely valid. I've gone into the Finder in OS X, performed a "Go to Directory," pasted in the value of listofFiles
and seen all my files in the directory.
Why is listFiles()
returning null?
Upvotes: 0
Views: 987
Reputation: 9735
The File constructor with a String expects a path, not (the toString of) a URL.
Use a different constructor, for example new File(listofFiles.toURI())
. Or give it a path: new File(listofFiles.getPath())
.
Update: Or (as ugly as this may seem) try both File constructors, as Java-guru Kohsuke Kawaguchi suggests.
If only we had File(URL) constructor...
Upvotes: 2
Reputation: 140061
According to the Javadoc for File.listFiles()
:
Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
The fact that you are getting a null
return value indicates that the path you are passing into the File constructor does not point to a directory.
I suspect that passing the result of URL.toString()
to the File constructor is building a path that is not what you think it is. Instead, try something like
File f = new File(listofFiles.toURI());
In addition, you might want to log the value of f.getAbsolutePath()
to make sure that the path being read is the same as what you expect.
Upvotes: 1