首先,我想说的是,之前发布的一些答案是完全正确的,但是我想告诉我,因为有时我们不能在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)



