Reputation: 1
When I run my code on Intellij Idea it work perfectly but when I run my code on the .jar (so build) there is a NullPointerException. Did someone know why and how to fix this ?
File folder = new
File(Main.class.getClassLoader().getResource("assets/maps/").getPath());
System.out.println(folder);
System.out.println(folder.listFiles());
for (File file : folder.listFiles()) {
if(file.getName().endsWith(".btdm"))
maps.add(getMap(file));
}
console :
file:\E:\Programmation\BabyTD\out\artifacts\BabyTD_jar\BabyTD.jar!\assets\maps
null
Exception in thread "main" java.lang.NullPointerException
at fr.picearth.Main.getMaps(Main.java:51)
at fr.picearth.Main.main(Main.java:26)
Upvotes: 0
Views: 1046
Reputation: 1026
Assuming assets/maps/
folder is part of your jar file, then you won't be able to access like any other folder on your drive.
IDE consider it as folder/file on drive so it works with getResource
.
What you could do is to use getResourceAsStream() method with the directory path, and the input Stream will have all the files name from that dir.
try getResourceAsStream
inplace of getResource
String respath = "/path_to_file";
InputStream in = sample2.class.getResourceAsStream(respath);
if ( in == null ){
throw new Exception("resource not found: " + respath);
}
InputStreamReader inr = new InputStreamReader(in, "UTF-8");
int len;
char cbuf[] = new char[2048];
while ((len = inr.read(cbuf, 0, cbuf.length)) != -1) {
// do something with cbuf
}
EDIT 2 :
if you are using java 7+ then you can also use
private Path getFolderPath() throws URISyntaxException, IOException {
URI uri = getClass().getClassLoader().getResource("folder").toURI();
if ("jar".equals(uri.getScheme())) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
return fileSystem.getPath("path/to/folder/inside/jar");
} else {
return Paths.get(uri);
}
}
Upvotes: 1
Reputation: 220842
If folder
is not a folder or cannot be accessed for some reason (including the fact that java.io.File
cannot open jar or other zip files like ordinary folders), then listFiles()
will return null. You've already seen this in your print out. You have to check prior to iterating:
File[] files = folder.listFiles();
if (files != null)
for (File file : files)
if(file.getName().endsWith(".btdm"))
maps.add(getMap(file));
However, you probably want to work with java.util.zip.ZipFile
instead
Upvotes: 1