问题已解决,请查看下面的帖子
我想使用Java将文件从一个.jar复制到另一个.jar,但不是所有文件都需要被复制。我只想复制一个特定的文件夹,该文件夹还可能包含子文件夹。我已经有了将文件从一个jar复制到另一个jar的代码:
public static void copyFiles(final File file) throws IOException {
final JarFile targetJar = new JarFile(file);
final JarOutputStream output = new JarOutputStream(new FileOutputStream(file));
final JarFile localJar = new JarFile(new File(JarEditor.class.getProtectionDomain().getCodeSource().getLocation().getFile()));
// WRAPPER_CONTENT is a String[] which contains all names of the files i want to copy
for (final String entryName : StringResource.WRAPPER_CONTENT) {
final JarEntry entryToCopy = localJar.getJarEntry(entryName);
final JarEntry targetEntry = new JarEntry(entryName);
output.putNextEntry(targetEntry);
final InputStream input = localJar.getInputStream(entryToCopy);
final byte[] buffer = new byte[10240];
int readByte = 0;
while ((readByte = input.read(buffer)) >= 0) {
output.write(buffer, 0, readByte);
}
}
output.flush();
output.close();
localJar.close();
targetJar.close();
}
目前,我通过运行硬编码的文件名列表来复制文件。但是我更喜欢一种更灵活的方式,以便我可以添加和删除我的jar资源,并且仍然可以正常工作。它们都位于jar中相同的父文件夹中。那么,如何遍历该文件夹并仅复制这些文件呢?
另外值得一提的是,所有需要复制的文件都位于我的运行时jar文件中,您可能已经从我的代码中看到了这一点。
感谢您的帮助 Baschdi