栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

      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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437299.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号