【Java】# 日常开发中遇到的问题(二)

1. 将List按照一定的大小分成多个list

1.1 com.google.common.collect.Lists

maven依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version>
</dependency>

image-20221121111704892

使用示例

// 将 devDeviceList 按 100 的大小进行分割
List<List<JSONObject>> deviceList = Lists.partition(devDeviceList, 100);

1.2 org.apache.commons.collections4

maven依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

image-20221121112919236

使用示例

List<List<JSONObject>> subLists = ListUtils.partition(list, 100);

2. 判断一个日期是否在昨天10点之后

使用 Calendar

public static boolean judgeDate(Date date) {
    Calendar cal = Calendar.getInstance();
    // 日期 设置为昨天
    cal.add(Calendar.DATE, -1);
    // 时间设置为昨天 10:00:00.0
    cal.set(Calendar.HOUR_OF_DAY, 10);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0); // 【比较重要的地方】
    return date.after(cal.getTime());
}

3. 判断当前时间是否大于某个时间

时间点 HH:mm:ss 比较 —— LocalTime

public static boolean timeCompare(String time) {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
    LocalTime lt = LocalTime.parse(time, dtf);
    return LocalTime.now().isAfter(lt);
}

日期 yyyy-MM-dd 比较 —— LocalDate

4. 上传文件到企业微信

/**
 * 上传文件到企业微信服务器
 *
 * @param filePath 本地文件所处位置
 * @param key      调用接口凭证, 机器人webhookurl中的key参数
 * @return
 * @throws Exception
 */
public static JSONObject uploadFile2qyWechat(String filePath, String key) throws Exception {
    /**
     * ========================= 企业微信官方给的示例 ============================
     *
     * POST https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=693a91f6-7xxx-4bc4-97a0-0ec2sifa5aaa&type=file HTTP/1.1
     * Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
     * Content-Length: 220
     *
     * ---------------------------acebdf13572468
     * Content-Disposition: form-data; name="media";filename="wework.txt"; filelength=6
     * Content-Type: application/octet-stream
     *
     * mytext
     * ---------------------------acebdf13572468--
     */
    
    // 返回结果
    String result = null;
    File file = new File(filePath);
    if (!file.exists() || !file.isFile()) {
        throw new IOException("文件不存在");
    }
    
    // ====================================== 开始构造请求体 =====================================
    // POST https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=693a91f6-7xxx-4bc4-97a0-0ec2sifa5aaa&type=file HTTP/1.1
    String uploadFileUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=KEY&type=file";
    URL url = new URL(uploadFileUrl.replace("KEY", key));
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    
    // 设置请求头
    // Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
    // Content-Length: 220(可以不用设置)
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");
    
    // 设置边界 其中 acebdf13572468 可自定义
    String boundary = "-------------------------acebdf13572468";
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    // 请求正文信息
    // ---------------------------acebdf13572468
    // Content-Disposition: form-data; name="media";filename="wework.txt"; filelength=6
    // Content-Type: application/octet-stream

    // 文件内容
    OutputStream out = new DataOutputStream(conn.getOutputStream());
    String builder = "\r\n" + "\r\n" +
        // 边界的基础上多两个 -
        "--" + boundary + "\r\n" +
        "Content-Disposition: form-data;name=\"media\"; filename=\"" +
        new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +
        "_系统使用情况统计.xlsx" +
        "\"; filelength=" +
        file.length() +
        "\r\n" +
        "Content-Type:application/octet-stream\r\n\r\n";
    out.write(builder.getBytes(StandardCharsets.UTF_8));
    DataInputStream din = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] buffer = new byte[1024];
    while ((bytes = din.read(buffer)) != -1) {
        out.write(buffer, 0, bytes);
    }
    din.close();

    // 结尾部分
    // ---------------------------acebdf13572468
    byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8);
    out.write(foot);
    out.flush();
    out.close();
    if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
        BufferedReader reader = null;
        try {
            StringBuilder strBuf = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String lineString = null;
            while ((lineString = reader.readLine()) != null) {
                strBuf.append(lineString);

            }
            result = strBuf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
    return JSONObject.parseObject(result);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LRcoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值