简体   繁体   中英

Get directory from classpath (getting a file now)

I want to search for files in a directory. Therefore I want to get the directory in a File object but i'm getting a file instead of a directory. This is what I'm doing, it prints false but I want it to be true.

URL url = getClass().getResource("/strategy/viewconfigurations/");
File folder = new File(url.toString());
System.out.println(folder.isDirectory());

How can I load this way a directory?

It seems path or String you will got from the URL object cause problem.
You passed file path which you will got from the url.toString() .

You need to change below line

File folder = new File(url.toString());  

with this line

File folder = new File(url.getPath());  

You need path of that folder which will you get from URL.getPath() function.

I hope this is what you need.

If you need an alternative for Java 7+ to Yagnesh Agola's post for finding a directory from a classpath folder, you could you also the newer java.nio.file.Path class.

Here is an example:

URL outputXml = Thread.currentThread().getContextClassLoader().getResource("outputXml");
if(outputXml == null) {
    throw new RuntimeException("Cannot find path in classpath");
}
Path path = Paths.get(outputXml.toURI());

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