**
##将文件里的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();
}
}
读取文件后进行操作再写回
最新推荐文章于 2023-12-29 23:23:24 发布