ログファイルのリストがあり、特定の行の最新版が含まれているファイルを見つける必要があります。この行を含む可能性があるのは、すべてまたはまったくありません。
ファイルの行は次のようになります。
2013/01/06 16:01:00:283 INFO ag.doLog: xxxx xxxx xxxx xxxx
そして、私は行が必要です
xx/xx/xx xx:xx:xx:xxx INFO ag.doLog: the line i need
私はファイルの配列を取得する方法を知っています。逆方向にスキャンすると、各ファイルの最新の行を見つけることができます(存在する場合)。
最大の問題は、ファイルが大きくなる可能性があり(2k行?)、比較的高速な方法(数秒)で行を見つけたいので、提案を受け付けています。
個人的なアイデア:ファイルにX時間の行がある場合、X時間より前に行が見つからなかったファイルはスキャンしないでください。これには、すべてのファイルを同時に検索する必要がありますが、方法がわかりません。
Atmはコードが壊れており、メモリが不足していると思います。
コード:
if(files.length>0) { //in case no log files exist
System.out.println("files.length: " + files.length);
for(int i = 0; i < files.length; i++) { ///for each log file look for string
System.out.println("Reading file: " + i + " " + files[i].getName());
RandomAccessFile raf = new RandomAccessFile(files[i].getAbsoluteFile(), "r"); //open log file
long lastSegment = raf.length(); //Finds how long is the files
lastSegment = raf.length()-5; //Sets a point to start looking
String leido = "";
byte array[] = new byte[1024];
/*
* Going back until we find line or file is empty.
*/
while(!leido.contains(lineToSearch)||lastSegment>0) {
System.out.println("leido: " + leido);
raf.seek(lastSegment); //move the to that point
raf.read(array); //Reads 1024 bytes and saves in array
leido = new String(array); //Saves what is read as a string
lastSegment = lastSegment-15; //move the point a little further back
}
if(lastSegment<0) {
raf.seek(leido.indexOf(lineToSearch) - 23); //to make sure we get the date (23 characters long) NOTE: it wont be negative.
raf.read(array); //Reads 1024 bytes and saves in array
leido = new String(array); //make the array into a string
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(leido.substring(0, leido.indexOf(" INFO "))); //get only the date part
System.out.println(date);
//if date is bigger than the other save file name
}
}
}