Mert Onur
Mert Onur

Reputation: 161

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.

Upvotes: 2

Views: 676

Answers (3)

Kayaman
Kayaman

Reputation: 73558

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.

Upvotes: 4

Ivan
Ivan

Reputation: 8758

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.

Upvotes: 1

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

Upvotes: 1

Related Questions