Java网络爬虫 爬取图片

嘿嘿,
半小时不见,我又来了

import java.io.*;
import java.net.*;

public class Test {

    static int index = 100;
    static String format = ".png";
    static String url = "https://cdn.heweather.com/cond_icon/";
    static String fileUrl = "C:\\Users\\admin\\Desktop";
    static String folderName = "\\imgTemp";

    public static void main(String[] args) throws IOException {
        hashFolder(fileUrl + folderName);
        String url;
        while ((url = getUrl()) != null) {
            HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
            if (connection.getResponseCode() == 200) {
                InputStream put = connection.getInputStream();
                File file = new File(getFileUrl());
                if (!file.exists()) file.createNewFile();
                OutputStream out = new FileOutputStream(file);
                byte[] buff = new byte[1024];
                int stream;
                while ((stream = put.read(buff)) > 0) out.write(buff, 0, stream);
                put.close();
                out.close();
            }
        }
        System.out.println("over");
    }

    static String getUrl() {
        if (index >= 1000) return null;
        return url + index++ + format;
    }

    static String getFileUrl() {
        return fileUrl + folderName + '\\' +index + format;
    }

    static void hashFolder(String url) {
        File file = new File(url);
        if (file.isDirectory()) deleteFolder(file);
        if (file.exists()) file.delete();
        file.mkdir();
    }

    static void deleteFolder(File folder) {
        for (File file: folder.listFiles())
            if (file.isFile()) file.delete();
            else deleteFolder(file);
    }
}

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值