批量从网上下载图片、zip等文件到本地[java爬虫]

系统管理员 2022-05-28 04:59 294阅读 0赞

程序

  1. public static void download(HFUTRequest httprequest,String url,String id) throws IOException{
  2. File fileDir=new File("E:\\zipFile");
  3. if(!fileDir.exists()){
  4. fileDir.mkdirs();
  5. }
  6. //图片或zip下载保存地址
  7. String filename="E:\\zipFile\\"+id+".zip";
  8. File file=new File(filename);
  9. if(file.exists()){
  10. file.delete();
  11. }
  12. BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(filename));
  13. try {
  14. HttpEntity entity=httprequest.getEntityByHttpGetMethod(url);
  15. int i=-1;
  16. byte[] byt= EntityUtils.toByteArray(entity);
  17. bw.write(byt);
  18. System.out.println("文件下载成功!");
  19. } catch (ClientProtocolException e) {
  20. e.printStackTrace();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. bw.close();
  25. }

解读

在上述的程序中:

  1. byte[] byt= EntityUtils.toByteArray(entity);

很多人提供的源码是:

  1. byte[] byt=new byte[1024];

或者:

  1. byte[] byt=new byte[10*1024];

有些是可行的,有些会导致下载的文件没办法解压。所以使用:

  1. byte[] byt= EntityUtils.toByteArray(entity);

这种方式就很完美了。

发表评论

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

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

相关阅读