下载远程URL文件
/** * 下载文件 * * @param path 文件链接地址, 如:www.abc.com/file/abc.png * @param savePath 文件保存地址, 如: F://test/a.png * @throws IOException */ public static void down(String path, String savePath) throws IOException {
if (StringUtils.isNotEmpty(path)) {
URL u = new URL(path);
InputStream in = u.openStream();
byte[] bb = new byte[in.available()];
in.read(bb);
FileOutputStream out = new FileOutputStream(savePath);
out.write(bb);
out.close();
}
}
(在本地测试时,上面的方式在下载大文件时会出错,因为byte容量有限,无法一次性读取出文件所有信息)
第二种方式:引入commons-io.jar
/** * 下载文件 * * @param fileUrl url链接 * @param savePath 文件保存路径 * @throws IOException */ private void downFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
byte[] by = IOUtils.toByteArray(url);
OutputStream os = new FileOutputStream(new File(savePath));
IOUtils.write(by, os);
IOUtils.closeQuietly(os);
}
还没有评论,来说两句吧...