下载远程URL文件

我就是我 2022-06-04 05:15 322阅读 0赞
  1. /** * 下载文件 * * @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 {
  2. if (StringUtils.isNotEmpty(path)) {
  3. URL u = new URL(path);
  4. InputStream in = u.openStream();
  5. byte[] bb = new byte[in.available()];
  6. in.read(bb);
  7. FileOutputStream out = new FileOutputStream(savePath);
  8. out.write(bb);
  9. out.close();
  10. }
  11. }

(在本地测试时,上面的方式在下载大文件时会出错,因为byte容量有限,无法一次性读取出文件所有信息)

第二种方式:引入commons-io.jar

  1. /** * 下载文件 * * @param fileUrl url链接 * @param savePath 文件保存路径 * @throws IOException */ private void downFile(String fileUrl, String savePath) throws IOException {
  2. URL url = new URL(fileUrl);
  3. byte[] by = IOUtils.toByteArray(url);
  4. OutputStream os = new FileOutputStream(new File(savePath));
  5. IOUtils.write(by, os);
  6. IOUtils.closeQuietly(os);
  7. }

发表评论

表情:
评论列表 (有 0 条评论,322人围观)

还没有评论,来说两句吧...

相关阅读