如何将jar内的文件复制到jar外? [英] How to copy file inside jar to outside the jar?

查看:70
本文介绍了如何将jar内的文件复制到jar外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 jar 中复制一个文件.我正在复制的文件将被复制到工作目录之外.我做了一些测试,我尝试的所有方法都以 0 字节文件结束.

I want to copy a file from a jar. The file that I am copying is going to be copied outside the working directory. I have done some tests and all methods I try end up with 0 byte files.

编辑:我希望通过程序而不是手动复制文件.

EDIT: I want the copying of the file to be done via a program, not manually.

推荐答案

首先我想说之前贴的一些答案是完全正确的,但我想给出我的,因为有时我们不能使用开源库在 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 答案

这篇关于如何将jar内的文件复制到jar外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆