gpt4 book ai didi

java - 格式化后拆分字符串并拼接的方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:35:17 24 4
gpt4 key购买 nike

我想拆分来自日志文件的字符串,格式化拆分的字符串,再次连接它,然后再次打印格式化的字符串。目前,代码只是逐行打印文件,而我想要的其余部分仍然存在。

我的代码是:

   try                
{
String strpath="/var/date.log";
FileReader fr = new FileReader(strpath);
BufferedReader br = new BufferedReader(fr);
String ch;
String[] Arr;
do
{
ch = br.readLine();
if (ch != null)
out.print(ch+"<br/>");
}
while (ch != null);
fr.close();
}
catch(IOException e){
out.print(e.getMessage());
}

日志文件的内容:

[1322110800] LOG ROTATION: DAILY[1322110800] LOG VERSION: 2.0[1322110800] CURRENT HOST STATE: arsalan.hussain;DOWN;HARD;1;CRITICAL - Host Unreachable (192.168.1.107)[1322110800] CURRENT HOST STATE: localhost;UP;HARD;1;PING OK - Packet loss = 0%, RTA = 0.06 ms[1322110800] CURRENT HOST STATE: musewerx-72c7b0;UP;HARD;1;PING OK - Packet loss = 0%, RTA = 0.27 ms[1322110800] CURRENT HOST STATE: sharepoint2;DOWN;HARD;1;CRITICAL - Host Unreachable (192.168.1.100)

I want to split this file per line on "]" and then get content in square brackets, format it in long date time and then concatenate it with the remaining line and print it.

This should be done with every line of the file.

This will give the formatted date:

String dat="1324649468000";
Date d = new Date(Long.valueOf(dat));

最佳答案

您可以使用这个简单的代码片段来进行转换:

String line = "[1322110800] LOG ROTATION: DAILY";
Pattern pt = Pattern.compile("\\[(\\d+)\\]");
Matcher m = pt.matcher(line);
if (m.find()) {
Date dt = new Date(Long.parseLong(m.group(1)) * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
line = m.replaceFirst('['+ sdf.format(dt) +']');
}

System.out.println(line);

输出

[11-24-2011 00:00:00] LOG ROTATION: DAILY

关于java - 格式化后拆分字符串并拼接的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com