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

时间:2016-03-22 10:22:50

标签: java jar copy

解决了,请参阅我的帖子

我想使用java将文件从一个.jar复制到另一个.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();
}

目前我通过运行硬编码的名称列表来复制文件。但是id更喜欢更灵活的方式,所以我可以添加和删除我的jar中的资源,它仍然可以工作。它们在jar中都有相同的父文件夹。那么我如何浏览那个文件夹并只复制这些文件呢?

也许值得一提的是,所有要复制的文件都位于我的运行时来自的jar文件中,因为你可能从查看我的代码中找到了。

感谢您的帮助 Baschdi

1 个答案:

答案 0 :(得分:0)

我猜运气不好。我现在一直在寻找解决方案,当我创建这个线程时,我设法找到了解决方案。我只是检查jarentry的名称是否以我要复制的文件夹的名称开头。如果是这样,我使用与上面相同的方法将jarentry复制到另一个jar。解决