简体   繁体   中英

listFiles() method in Java doesn't work in .jar

I have a "Pictures" folder in my project like this: link

I want to find the number of files in some of these folders.

I'm using: int length = new File("./Pictures/1").listFiles().length which works perfectly fine when I run the IDE. However when I convert my project to .jar File I get a NullPointerException.

A jar file is basically a zip file. Your code would be looking for the Pictures directory on your file system, not inside the jar file. To access files inside a jar file (also works outside of jar, it searches from the classpath) you can use Class.getResource() (and getResourceAsStream() ).

However I'm not certain whether it's possible to use those for file listings as you want, they're mostly used for retrieving single resources from the classpath.

You cannot use File with jar entries. You must locate the jar file and treat it as a zip file.

You use relative paths to folders and when you run from IDE relative paths work correctly since they are relative to project root directory. But when you run jar JVM assumes that relative paths are relative to the directory where jar is located.

If you just want to check how File.listFiles() work then you can use full path to that folder.

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