博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java批量下载图片和写入文件
阅读量:4156 次
发布时间:2019-05-25

本文共 5532 字,大约阅读时间需要 18 分钟。

版权声明:本博客的所有原创内容皆为作品作者所有

转载请注明:来自ZJBLOG 链接:www.zjhuiwan.com

 

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

[{

    "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数组遍历。获取到的图片下载,文字写入文档。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

 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包:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

   <!-- 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>

运行结果:

保存到本地:

156255827943559002753.png

你可能感兴趣的文章
字节对齐
查看>>
把类成员函数封装成线程API所需要的函数
查看>>
HTTP Live Streaming直播(iOS直播)技术分析与实现
查看>>
Ribbon界面图标可以直接用PNG做透明图标
查看>>
向其他软件窗口、控件发送消息的方法
查看>>
word或者pdf文件全部保存为图片的方法
查看>>
VS2010下SQLite3生成lib库文件
查看>>
sqlite3的helloworld
查看>>
MFC下支持中文的SQLite3封装类使用
查看>>
简单高效的多线程日志类
查看>>
研华USB4711A采集卡高速中断模式采集总结
查看>>
从零起步CMFCToolBar用法详解
查看>>
CMFCRibbonStatusBar用法
查看>>
CMFCControlRendererInfo类的参数
查看>>
史上最详细MFC调用mapX5.02.26步骤(附地图测试GST文件)
查看>>
CMFCShellListCtrl使用方法
查看>>
mapnik的demo运行
查看>>
python支持下的mapnik安装
查看>>
milvus手册
查看>>
查看pytorch基于cuda 的哪个版本
查看>>