Non*_*eSL 3 java resources file guava
我正在尝试将项目中的资源复制到磁盘上的另一个位置.到目前为止,我有这个代码:
if (!file.exists()){
try {
file.createNewFile();
Files.copy(new InputSupplier<InputStream>() {
public InputStream getInput() throws IOException {
return Main.class.getResourceAsStream("/" + name);
}
}, file);
} catch (IOException e) {
file = null;
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
并且它工作正常,但是这个InputSupplier类已被弃用,所以我想知道是否有更好的方法来做我想做的事情.
请参阅Guava InputSupplier类的文档:
对于
InputSupplier<? extends InputStream>,请ByteSource改为使用.对于InputSupplier<? extends Reader>,使用CharSource.的实现InputSupplier不属于这些类别的一个没有任何的方法中获益common.io,并应使用不同的接口.该界面计划于2015年12月删除.
所以在你的情况下,你正在寻找ByteSource:
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Guava Wiki的此部分.
如果您正在寻找纯Java(无外部库)版本,则可以执行以下操作:
try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("/" + name)) {
Files.copy(is, Paths.get("C:\\some\\file.txt"));
} catch (IOException e) {
// An error occurred copying the resource
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅适用于Java 7及更高版本.