I need to get a folder within a jar file.
The folder is name postman and contains some JSON files. My purpose is to get that folder as a File object, list the files to do some actions on names and parse the content for some other actions.
The problem I got is that I can't get that folder and his content.
After reading some documentation and topics from here, I tried many things, increase my understanding about that kind of stuff.
Now I got this :
URL url = SasPostman.class.getClassLoader().getResource(POSTMAN_RESOURCES_PATH);
// url output -> jar:file:/home/randomFolder/myJarFile.jar!/postman
try {
JarURLConnection connection = (JarURLConnection) url.openConnection();
File myFolder = new File(connection.getJarFileURL().toURI());
if(myFolder.exists() && myFolder.isDirectory()) {
// some code
}
MyFolder exist but isn't a directory. I added some log to try to understand each steps, but I am not able to draw conclusion from it.
connection.getURL() results to jar:file:/home/randomFolder/myJarFile.jar!/postman
connection.getURL().toURI() results to jar:file:/home/randomFolder/myJarFile.jar!/postman
connection.getJarFileURL().toURI() results to jar:file:/home/randomFolder/myJarFile.jar
Even if I use the paths endind with the folder name, myFolder isn't the expected directory.
I probably miss something or maybe it should be done in another way. Maybe by coying the whole folder I need into another location ? I don't know..
I also looked at some documentation of using ZipFile but I just see how to use it to retrieve one file. Or I need to get all the files from my folder.
Any help would be appreciated !
You could try this and adapt it as necessary:
import java.util.Map;
import java.util.HashMap;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
public class ZipFSPUser {
public static void main(String[] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:///tmp/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path jsonDir = zipfs.getPath("/root/a");
try (DirectoryStream<Path> paths = Files.newDirectoryStream(jsonDir, "*.json")) {
paths.forEach(System.out::println);
}
}
}
}