读取文件后进行操作再写回

**

##将文件里的utc时间转为北京时间

**使用正则匹配时间 进行操作**

**
/**
     * 读文件 再写文件
     *
     * @param filePath 文件路径
     */
	public void FileContentTime(String filePath) {
        try {
            List<String> fileContentList = FileUtil.readUtf8Lines(filePath);
            StringBuilder sb = new StringBuilder();
            if (!fileContentList.isEmpty()) {
                for (String lineContent : fileContentList) {
                    String newLine = replaceTime(lineContent);
                    sb.append(newLine).append("\n");
                }
                createFile(sb.toString(), filePath);
            }
        }catch (Exception e){
            log.error(MsgPrefixKit.gen("下载失败{},未找到文件"),e.getMessage());
        }
    }


	/**
     * 时间 utc转北京
     *
     * @param lineContent 行内容
     * @return 替换后的行
     */
    private String replaceTime(String lineContent) {
        String content = lineContent;
        String pattern = "[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-			(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))\\s+([0-1]?[0-9]|2[0-3]):([0-5]		[0-9]):([0-5][0-9]).[0-9]{1,6}";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(lineContent);
        List<String> timeList = new ArrayList<>();
        List<String> stringList = new ArrayList<>();
        while (m.find()) {
            stringList.add(m.group());
            long bjt = DateUtil.parse(m.group(), "yyyy-MM-dd HH:mm:ss.SSS").getTime() + 		(8 * 3600 * 1000);
            String time = DateUtil.format(new Date(bjt), "yyyy-MM-dd HH:mm:ss.SSS");
            timeList.add(time);
        }
        for (int i = 0; i < timeList.size(); i++) {
            content = content.replaceAll(stringList.get(i), timeList.get(i));
        }
        return content;
    }

     /**
     * 写文件
     * @param str 文件内容
     * @param file 文件路径
     */
	public void createFile(String str, String filePath) {
        FileWriter fw = null;
        try {
            //生成文件
            fw = new FileWriter(filePath);
            fw.write(str);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值