我正在尝试将项目中的资源复制到磁盘上的另一个位置。到目前为止,我有以下代码:
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;
}
}
它可以正常工作,但是InputSupplier
不推荐使用该类,所以我想知道是否有更好的方法可以完成我想做的事情。
请参阅GuavaInputSupplier
类的文档:
对于
InputSupplier<? extends InputStream>
,请ByteSource
改用。对于InputSupplier<? extends Reader>
,使用CharSource
。的实现InputSupplier
不属于这些类别的一个没有任何的方法中获益common.io
,并应使用不同的接口。该界面计划于2015年12月删除。
因此,在您的情况下,您正在寻找ByteSource
:
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
有关更多信息,请参见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
}
请注意,这仅对Java 7及更高版本有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句