Issue
I try to loop over all files in a certain folder in my resources (I added this folder myself in eclipse by doing new->folder). Whatever I try it keeps giving a null exception on the line where I try to get the folder. As I need to loop over its content getting it as a stream or something won't work. I tried many approaches, but for example these two gave me the error:
File folder = new File(Thread.currentThread().getContextClassLoader().getResource("schematics").getPath());
This wrapped inside a try catch did also not work:
File folder = new File(getClass().getClassLoader().getResource("schematics").toURI());
My file structure (class where I try to access the schematics is HeavenStructureManager's initialiser):
EDIT This project is a minecraft plugin, bundled to a jar by maven and run by the spigotmc minecraft jar. Their api provides a function getResource() but that gives a InputStream. As I would like to dynamically get all files inside a folder that does not work for me. I unpacked my jar file to check where the schematic is, and it looked like this:
Solution
Below is a code example to iterate through the contents of a jar file, list them and write the contents to a new file.
Current run directory: .
Jar file directory: ./plugins/org.alloytools.alloy.dist.jar
Output directory: ./unzipped
package com.serge;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class JarFileReader {
public static void main(String[] args) {
try {
File file = new File("plugins/org.alloytools.alloy.dist.jar");
FileInputStream fileInputStream = new FileInputStream(file);
JarInputStream jarInputStream = new JarInputStream(fileInputStream);
FileOutputStream outputStream = null;
File unzippedDir = new File("unziped");
while(jarInputStream.getNextEntry() != null) {
JarEntry entry = jarInputStream.getNextJarEntry();
// list the contents of the jar file
System.out.println(entry.toString());
// write contents of a file within the jar file to a new file
if("help/Nav.html".equals(entry.getName())) {
new File(unzippedDir + "/" + entry.getName().substring(0, entry.getName().indexOf("/"))).mkdir();
File unzippedFile = new File(unzippedDir + "/" + entry.getName());
unzippedFile.createNewFile();
outputStream = new FileOutputStream(unzippedFile);
byte[] bytes = new byte[1024];
int length = 0;
while((length = jarInputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, length);
}
}
}
outputStream.close();
jarInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Answered By - Serge