我的 jar 内的资源文件夹包含一个包含多个二进制文件的目录。我正在尝试使用此代码来提取它们:
try(InputStream is = ExternalHTMLThumbnail.class.getResourceAsStream("/wkhtmltoimage")) {
Files.copy(is, Paths.get("/home/dan/wkhtmltoimage");
}
这会引发错误
java.nio.file.NoSuchFileException: /home/dan/wkhtmltoimage
来自
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
在 UnixException.java 中。即使在 Files.java 中传递了正确的选项:
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
来自Files.copy
。当然没有!这就是为什么我要努力做到这一点。我还不太了解 Path
和 Files
来正确执行此操作。提取目录及其所有内容的最佳方法是什么?
由于 Files.copy
声明的文档而感到困惑
By default, the copy fails if the target file already exists or is a symbolic link
(如果目标文件也不存在,显然会失败?)
并列出了可能的异常,而NoSuchFileException
不是其中之一。
最佳答案
如果您使用Guava :
URL url = Resources.getResource(ExternalHTMLThumbnail.class, "wkhtmltoimage");
byte[] bytes = Resources.toByteArray(url);
Files.write(bytes, new File("/my/path/myFile"));
您当然可以将其全部链接到一行中;我声明了变量以使其更具可读性。
关于java - 从 Java 7 中运行的 jar 中提取资源文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24173337/