New lines in a file
I'm trying to find a good way to get new lines in a file, and while this works it also uses 100% CPU and is driving me nuts. At least the profiler says this is .run is using the most, and taskmanager gives it 100%. The file name changes every day.
package net.st0rm.ss.loghandlers;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import net.st0rm.ss.Log;
import net.st0rm.ss.gamecmdhandlers.GameCommandHandler;
import net.st0rm.ss.irc.IRC;
publicabstractclass LogHandler{
publicstatic ArrayList<GameCommandHandler> gameCmdHandlers =new ArrayList<GameCommandHandler>();
private BufferedReader reader =null;
private File directory =null;
private LogReadThread thread =null;
private String thisLine =null;
privateboolean skip =true;
/**
* Time to wait between reads
*/
private Long delay = 100;
/**
* Creates a new instance
* @param directory Directory of the files used
* @param skip Should the reader skip lines already existing?
*/
public LogHandler(File directory,boolean skip){
this.directory = directory;
this.skip = skip;
}
public String getFileName(){return"";};
privateclass LogReadThreadextends Thread{
publicboolean stop =false;
publicvoid run(){
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND,59);
StringBuilder sb =new StringBuilder(1000);
new Timer("Restart Timer").schedule(
new TimerTask(){
publicvoid run(){
try{
Thread.sleep(3000);
}catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
IRC.getInstance().msg("Restarting reader \"" + this.getClass().getSimpleName() +"\" for the new day.");
LogHandler.this.restartReader();
}
}
,c.getTime(), 3600000*24);
try{
reader =new BufferedReader(new FileReader(directory.getAbsolutePath() +"/" + getFileName()));
if (skip)while ((reader.readLine()) !=null);
while (!stop){
try{
Thread.sleep(delay);
}catch (InterruptedException e){ System.out.println("Thread Interupted!");}
while ((sb.append(reader.readLine())).toString() !=null){ onNewLine(sb.toString()); sb.delete(0, sb.length());}
}
reader.close();
}catch (IOException e){
Log.log(e);
}
}
}
/**
* Call to re-start the file stream
*
*/
publicvoid restartReader(){
if (thread !=null) thread.stop =true;
thread =new LogReadThread();
thread.start();
}
/**
* Called when a new line is added to the file
* @param line The line added
*/
publicvoid onNewLine(String line){}
}

