小编典典

如何将jar中的文件复制到jar中?

java

我想从罐子中复制文件。我要复制的文件将被复制到工作目录之外。我已经做过一些测试,所有尝试使用的方法都以0字节文件结尾。

编辑 :我希望通过程序而不是手动完成文件的复制。


阅读 352

收藏
2020-09-08

共1个答案

小编典典

首先,我想说的是,之前发布的一些答案是完全正确的,但是我想告诉我,因为有时我们不能在GPL下使用开放源代码库,或者因为我们懒得下载jarXD或其他文件无论您的理由在这里,还是一个独立的解决方案。

下面的函数将资源复制到Jar文件旁边:

  /**
     * Export a resource embedded into a Jar file to the local file path.
     *
     * @param resourceName ie.: "/SmartLibrary.dll"
     * @return The path to the exported resource
     * @throws Exception
     */
    static public String ExportResource(String resourceName) throws Exception {
        InputStream stream = null;
        OutputStream resStreamOut = null;
        String jarFolder;
        try {
            stream = ExecutingClass.class.getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree
            if(stream == null) {
                throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file.");
            }

            int readBytes;
            byte[] buffer = new byte[4096];
            jarFolder = new File(ExecutingClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getPath().replace('\\', '/');
            resStreamOut = new FileOutputStream(jarFolder + resourceName);
            while ((readBytes = stream.read(buffer)) > 0) {
                resStreamOut.write(buffer, 0, readBytes);
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            stream.close();
            resStreamOut.close();
        }

        return jarFolder + resourceName;
    }

只需将ExecutingClass更改为您的类的名称,然后像这样调用它:

String fullPath = ExportResource("/myresource.ext");

为Java 7+编辑(为了您的方便)

正如GOXR3PLUS回答并由AndyThomas指出的那样,您可以使用以下方法实现此目标:

Files.copy( InputStream in, Path target, CopyOption... options)
2020-09-08