Java 如何正确使用 FileUtils IO?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19059244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:46:18  来源:igfitidea点击:

How to use FileUtils IO correctly?

javaselenium

提问by Buras

I tried to use method (credits to Shenyuan Lu):

我尝试使用方法(归功于沉远路):

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

Precisely:

恰恰:

org.apache.commons.io.FileUtils.copyURLToFile(driver.getCurrentUrl(), "C:\\Users\\myDocs\\myfolder\myFile.pdf");

org.apache.commons.io.FileUtils.copyURLToFile(driver.getCurrentUrl(), "C:\\Users\\myDocs\\myfolder\myFile.pdf");

However,Eclipseis underlining the copyURLToFileand suggesting to use copyFile. When I switch to copyFile, it suggests to use copyURLToFileagain???

但是,Eclipse强调copyURLToFile并建议使用copyFile. 当我切换到 时copyFile,它建议copyURLToFile再次使用???

采纳答案by ddavison

According to the FileUtils#copyURLToFile() API...

根据FileUtils#copyURLToFile() API...

The first parameter needs to be a URLobject, and the second parameter needs to be a FileObject. You are passing Strings as both args. Try...

第一个参数需要是一个URL对象,第二个参数需要是一个File对象。您将字符串作为两个参数传递。尝试...

org.apache.commons.io.FileUtils.copyURLToFile(new URL(driver.getCurrentUrl()), new File("C:\Users\myDocs\myfolder\myFile.pdf"));

Also, since this method throws an exception, you either need to make your method throw an exception, or surround the statement in a try {} catch{} block.

此外,由于此方法抛出异常,您需要让方法抛出异常,或者将语句括在 try {} catch{} 块中。

e.g.

例如

try {
    org.apache.commons.io.FileUtils.copyURLToFile(new URL(driver.getCurrentUrl()), new File("C:\Users\myDocs\myfolder\myFile.pdf"));
} catch (Exception x) { x.printStackTrace(); }