I am attempting to store some resources for my program within the runnable jar created through Intellij and then extract those files at runtime after receiving some user input. The folders are located on the root of the jar. I have got it to successfully extract the files as intended but the problems begin when the jar is renamed. As in applic1.jar to applic2.jar. Does anyone know why it is behaving in this manner?
This is the method that performs the extractions. Modified version of: How can I get a resource "Folder" from inside my jar File?
File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
boolean inDirectory = false;
if (jarFile.isFile()) { //run in JAR
try {
JarFile jar = new JarFile(jarFile);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry currentJar = entries.nextElement();
String name = currentJar.getName();
Path currentFile = Paths.get(name).getFileName();
if (name.startsWith(oldPath.replaceAll(Pattern.quote("\\"), "/"))) {
if (currentJar.isDirectory()) {
Files.createDirectories(Paths.get(newPath));
inDirectory = true;
} else {
if (Files.notExists(Paths.get(newPath), LinkOption.NOFOLLOW_LINKS)) {
Files.createDirectories(Paths.get(newPath).getParent());
}
BufferedInputStream source = new BufferedInputStream(jar.getInputStream(currentJar));
File dest = new File(newPath + (inDirectory ? "\\" + currentFile : ""));
FileOutputStream fos = new FileOutputStream(dest);
int read;
while ((read = source.read()) != -1) {
fos.write(read);
fos.flush();
}
fos.close();
source.close();
}
}
}
jar.close();
} catch (IOException e) {
e.printStackTrace();
}
} else { //run in IDE
copyAndRename(oldPath, newPath);
}