Java:如何将文件夹从一个jar包复制到另一个jar包?

3

问题已解决,请查看下面的帖子

我想使用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
1个回答

0

看来有些倒霉。我已经搜索解决方案有一段时间了,就在我创建这个线程的时候,我终于找到了解决方案。我只是检查Jarentry名称是否以我想要复制的文件夹的名称开头。如果是,我使用与上面相同的方法将Jarentry复制到其他JAR中。问题解决了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接