简体   繁体   中英

Why does this unit test say my directory doesn't exist when it does?

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?

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM