做爬虫功能时候,经常需要通过url将文件保存到本地。网上看到不少例子,代码都比较繁杂,需要自己读取文件流并输出流到文件。在这里,我们通过API来实现这个功能,代码简单清晰。
代码实现
/**
* @author FeianLing
* @date 2019/9/16
*/
public class FileUtil {
private FileUtil() {
//ignore this method
}
/**
* @param
* @param fileUrl
* @param filePath
* @return void
* @author FeianLing
* @date 2019/9/16
* @desc 通过url请求将文件保存到本地
*/
public static void saveFile(String fileUrl, String filePath) throws IOException {
URL url = new URL(fileUrl);
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileUtils.copyURLToFile(url, file);
}
}
测试代码
public static void main(String[] args) throws IOException {
String fileUrl = "https://blog.csdn.net/lingfeian/article/details/100052895";
String filePath = "D:/mnt/uploads/tmp/test.pdf";
FileUtil.saveFile(fileUrl, filePath);
}
代码看起来是不是简单了许多,这里的FileUtils.copyURLToFile使用的是commons-io1.3.2的包。