I have a problem. I want to make a programm, that takes a Log File and parse it line for line.
A Log looks like this:
"2014-02-14 14:26:37,836 INFO [org.jboss.msc] (main) JBoss MSC version 1.0.4.GA-redhat-1"
My code:
public static void main(String[] args) throws InterruptedException {
try
{
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("C:\\server.log"));
while ((sCurrentLine = br.readLine()) != null) {
String datetime = "";
String level = "";
String category = "";
String message = "";
String output = "";
if(sCurrentLine.length()<1){
}
else{
if (sCurrentLine.charAt(4)=='-' && sCurrentLine.charAt(7)=='-' && sCurrentLine.charAt(13)==':' && sCurrentLine.charAt(16)==':'){
String[] leerzeichen = sCurrentLine.split(" ");
String[] leerzeichenz = sCurrentLine.split(" ");
datetime = leerzeichen[0] + " " + leerzeichen[1];
level = leerzeichen[2];
category = leerzeichen[4];
int arraylength = leerzeichen.length;
for (int l=5; l<arraylength; l++){
message = message.concat(leerzeichen[l] + " ");
}
output = datetime + level + category + message;
} else {
message = message.concat(sCurrentLine);
output += message;
}
}
System.out.println(output);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The Program looks, if the beginning of the Line looks like this: 0000-00-00 00:00:00 If not, the Line is only a message in connection with the line before.
But I always get the Error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at javaapplication5.JavaApplication5.main(JavaApplication5.java:38)
But he reads some lines of the log. But not until the end of the log.
Can you help me? sorry for my English.
You have problem in line:
if (sCurrentLine.charAt(4)=='-' && sCurrentLine.charAt(7)=='-' && sCurrentLine.charAt(13)==':' && sCurrentLine.charAt(16)==':'){
You cannot assume that the line have at least 4, 7 or more characters.
Try changing it to this:
if (sCurrentLine.length() >= 16 && sCurrentLine.charAt(4)=='-' && sCurrentLine.charAt(7)=='-' && sCurrentLine.charAt(13)==':' && sCurrentLine.charAt(16)==':'){
The cause of error is quite straight forward; you first check if string has length > 1, and then directly ask for char at index 4 -- which is no guarantee to exists since all you know is thats length > 1.
Hence, add proper checking before trying to access char at index 4, and most of all, as said in comment by @VusP, add some print/debugging of the read string before trying to parse it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.