我想从罐子中复制文件。我要复制的文件将被复制到工作目录之外。我已经做过一些测试,所有尝试的方法最终都包含0个字节的文件。
编辑:我希望通过程序而不是手动完成文件的复制。
首先,我想说的是,之前发布的一些答案是完全正确的,但是我想告诉我,因为有时我们不能在GPL下使用开放源代码库,或者因为我们懒得下载jar XD或其他文件无论您的理由在哪里,都是独立的解决方案。
下面的函数将资源复制到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");
正如GOXR3PLUS回答并由Andy Thomas指出的那样,您可以使用以下方法实现此目标:
Files.copy( InputStream in, Path target, CopyOption... options)
有关更多详细信息,请参见GOXR3PLUS答案
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句