I want to split a string coming from a log file, format the split string, concatenate it again, then print the formatted string again. Currently, the code is just printing file line by line while the rest that I want is remaining.
My code is:
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());
}
Contents of log file:
[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));
You can use this simple code snippet to do that conversion:
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);
OUTPUT
[11-24-2011 00:00:00] LOG ROTATION: DAILY