如何在Java中将资源复制到另一个位置的文件
我正在尝试将项目中的资源复制到磁盘上的另一个位置。到目前为止,我有以下代码:如何在Java中将资源复制到另一个位置的文件,java,file,resources,guava,Java,File,Resources,Guava,我正在尝试将项目中的资源复制到磁盘上的另一个位置。到目前为止,我有以下代码: if (!file.exists()){ try { file.createNewFile(); Files.copy(new InputSupplier<InputStream>() { public InputStream getInput() throws IOException { return Main
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;
}
}
如果(!file.exists()){
试一试{
createNewFile();
文件。副本(新输入供应商(){
公共InputStream getInput()引发IOException{
返回Main.class.getResourceAsStream(“/”+名称);
}
},档案);
}捕获(IOE异常){
file=null;
返回null;
}
}
它工作正常,但InputSupplier类已被弃用,因此我想知道是否有更好的方法来完成我正在尝试的工作。请参阅番石榴的文档:
对于
InputSupplier,我刚刚找到了纯java解决方案,正要发布它,然后我看到了您的编辑。非常感谢!请注意,您展示的纯Java版本与Guava版本有一个重要区别:它甚至不尝试关闭资源流。Guava版本保证在复制后关闭流,无论复制成功与否。@ColinD他使用了“尝试使用资源”块,因此InputStream将自动关闭。@Pavitra:我的评论是指Nonamel发布的答案,该答案已被删除,而不是此评论所针对的答案。
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
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
}