Java批量写入文件和下载图片的示例代码

 更新时间:2020年09月17日 09:40:05   作者:zj  
这篇文章主要介绍了Java批量写入文件和下载图片的示例代码,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下

很久没有在WhitMe上写日记了,因为觉着在App上写私密日记的话肯定是不安全的,但是想把日记存下来。,然后看到有导出日记的功能,就把日记导出了(还好可以直接导出,不然就麻烦点)。导出的是一个html文件。可以直接打开,排版都还在。

看了下源码,是把日记存在一个json数组里了,图片还是在服务器,利用url访问,文字是在本地了。 但是想把图片下载到本地,然后和文字对应,哪篇日记下的哪些图片。

大概是如下的json数组。 大概有几百条,分别是头像、内容:文字||内容:图片、时间。 简单明了的json结构,就想着用java遍历保存到本地。

[{
  "avatar": "http://static.withme.cn/585****",
  "blocks": [{
    "content": "今天天气不错******",
    "type": "text"
  }, {
    "content": "http://static.withme.cn/84ac***",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/5af2c***",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/9a4e****",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/9ffdb***",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/da5e7db***",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/e6ccf3764***",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/73ca***",
    "type": "pic"
  }, {
    "content": "http://static.wi***",
    "type": "pic"
  }, {
    "content": "http://static.withme.cn/4cf7dde****",
    "type": "pic"
  }],
  "dateStr": "2018-09-03",
  "timeStr": "18:59:41"
},{...},...]

将json数组格式化确保正确然后转成json数组遍历。获取到的图片下载,文字写入文档。

 public static void main(String[] args) {
    CloseableHttpClient client = null;
    JSONArray jsonArray = JSONArray.parseArray(
      "[{
        "avatar": "http://static.withme.cn/585****",
        "blocks": [{
          "content": "今天天气不错******",
          "type": "text"
        }, {
          "content": "http://static.withme.cn/84ac***",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/5af2c***",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/9a4e****",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/9ffdb***",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/da5e7db***",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/e6ccf3764***",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/73ca***",
          "type": "pic"
        }, {
          "content": "http://static.wi***",
          "type": "pic"
        }, {
          "content": "http://static.withme.cn/4cf7dde****",
          "type": "pic"
        }],
        "dateStr": "2018-09-03",
        "timeStr": "18:59:41"
      },{...},{...},...]");
 
    try {
      for (int m = 0; m < jsonArray.size(); m++) {
        JSONObject jsonPas = jsonArray.getJSONObject(m);
        JSONArray array = JSONArray.parseArray(jsonPas.get("blocks").toString());
        String time = jsonPas.get("dateStr").toString();
        for (int j = 0; j < array.size(); j++) {
          JSONObject jsPas = array.getJSONObject(j); // 遍历 jsonarray 数组,把每一个对象转成 json 对象
          if (jsPas.get("type").equals("text")) {
            FileWriter fileWriter = null;
            try {
              String filePath = "f:/13/" + time;
              File dir = new File(filePath);
              // 检查放置文件的文件夹路径是否存在,不存在则创建
              if (!dir.exists()) {
                dir.mkdirs();// mkdirs创建多级目录
              }
              File checkFile = new File(filePath + "/text" + time + "-" + j + ".txt");
              // 检查目标文件是否存在,不存在则创建
              if (!checkFile.exists()) {
                checkFile.createNewFile();// 创建目标文件
              }
              // FileWriter(File file, boolean append),append为true时为追加模式,false或缺省则为覆盖模式
              fileWriter = new FileWriter(checkFile, true);
              String url = jsPas.get("content").toString();
              // 向目标文件中写入内容
              fileWriter.append(url);
              fileWriter.flush();
              System.out.println("写入成功!!");
            } catch (IOException e) {
              e.printStackTrace();
            } finally {
              try {
                fileWriter.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          if (jsPas.get("type").equals("pic")) {
            client = HttpClients.createDefault();
            String url = jsPas.get("content").toString();
            String path = "f:/13/" + time;
            // System.out.println(jsPas.get("content"));
            httpGetImg(client, url, path + "/pic" + time + "-" + j + ".jpg");
            System.out.println("ok");
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (client != null) {
        try {
          client.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
 
  /**
   * 发送get请求, 下载图片
   * 
   * @param url 路径
   * @return
   */
  public static void httpGetImg(CloseableHttpClient client, String imgUrl, String savePath) {
    // 发送get请求
    HttpGet request = new HttpGet(imgUrl);
    // 设置请求和传输超时时间
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
    // 设置请求头
    request.setHeader("User-Agent",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
    request.setConfig(requestConfig);
    try {
      CloseableHttpResponse response = client.execute(request);
      if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        FileUtils.copyInputStreamToFile(in, new File(savePath));
        System.out.println("下载图片成功:" + imgUrl);
      }
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    } finally {
      request.releaseConnection();
    }
  }

JAr包:

 <!-- apache io操作通用jar包 -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    
   <!-- httpclient 支持jar -->
  <dependency>
    <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
     <version>4.3.5</version>
   </dependency>
   <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.3.5</version>
   </dependency>

运行结果:

保存到本地:

以上就是Java批量写入文件和下载图片的示例代码的详细内容,更多关于Java批量写入和下载的资料请关注脚本之家其它相关文章!

相关文章

  • Spring Boot监听Redis Key失效事件实现定时任务的示例

    Spring Boot监听Redis Key失效事件实现定时任务的示例

    这篇文章主要介绍了Spring Boot监听Redis Key失效事件实现定时任务的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Lucene实现索引和查询的实例讲解

    Lucene实现索引和查询的实例讲解

    下面小编就为大家分享一篇Lucene实现索引和查询的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • Java泛型类型通配符和C#对比分析

    Java泛型类型通配符和C#对比分析

    下面小编就为大家带来一篇Java泛型类型通配符和C#对比分析。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • Spring详细讲解@Autowired注解

    Spring详细讲解@Autowired注解

    @Autowired注解可以用在类属性,构造函数,setter方法和函数参数上,该注解可以准确地控制bean在何处如何自动装配的过程。在默认情况下,该注解是类型驱动的注入
    2022-06-06
  • 基于Java利用static实现单例模式

    基于Java利用static实现单例模式

    这篇文章主要介绍了基于Java利用static实现单例模式,当在多个线程同时触发类的初始化过程的时候static不会被多次执行,下面我们一起进入文章看看具体要的原因
    2022-01-01
  • java接口自动化测试框架及断言详解

    java接口自动化测试框架及断言详解

    这篇文章主要介绍了java接口自动化测试框架及断言详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • java实现爬取知乎用户基本信息

    java实现爬取知乎用户基本信息

    这篇文章主要为大家介绍了一个基于JAVA的知乎爬虫,抓取知乎用户基本信息,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • Spring框架实现AOP添加日志记录功能过程详解

    Spring框架实现AOP添加日志记录功能过程详解

    这篇文章主要介绍了Spring框架实现AOP添加日志记录功能过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • linux查找安装jdk并配置JAVA_HOME的方法

    linux查找安装jdk并配置JAVA_HOME的方法

    这篇文章主要介绍了linux查找安装jdk,配置JAVA_HOME,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • java如何消除太多的if else判断示例代码

    java如何消除太多的if else判断示例代码

    这篇文章主要介绍了java如何消除太多的if else判断,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05

最新评论