且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将jar内的文件复制到jar外?

更新时间:2023-01-10 10:57:07

首先我想说之前贴的一些答案是完全正确的,但我想给出我的,因为有时我们不能使用开源库在 GPL 下,或者因为我们懒得下载 jar XD 或者您的原因在这里是一个独立的解决方案.

First of all I want to say that some answers posted before are entirely correct, but I want to give mine, since sometimes we can't use open source libraries under the GPL, or because we are too lazy to download the jar XD or what ever your reason is here is a standalone solution.

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

The function below copy the resource beside the Jar file:

  /**
     * 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 更改为您的类的名称,并像这样调用它:

Just change ExecutingClass to the name of your class, and call it like this:

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

针对 Java 7+ 进行编辑(为方便起见)

GOXR3PLUS 回答并由 Andy Thomas 您可以通过以下方式实现:


Edit for Java 7+ (for your convenience)

As answered by GOXR3PLUS and noted by Andy Thomas you can achieve this with:

Files.copy( InputStream in, Path target, CopyOption... options)

有关详细信息,请参阅GOXR3PLUS 答案