我试图在通过Intellij创建的可运行jar中为我的程序存储一些资源,然后在收到一些用户输入后在运行时提取这些文件。文件夹位于jar的根目录中。我已经按照预期成功提取文件但是重命名jar时会出现问题。与applic1.jar中的applic2.jar一样。有谁知道它为什么会以这种方式表现?
这是执行提取的方法。修改后的版本: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);
}