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?
According to the Javadoc for
File.listFiles():The fact that you are getting a
nullreturn 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 likeIn 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.