我正在开发一些必须读取日志文件的程序,我认为我在其中构建了一个智能机制,结果代码甚至无法编译......
我犯了一个很大的设计缺陷:如何修复它?
public class Reader implements Runnable {
private volatile boolean isReading;
private final File file;
public Reader(final File file) {
this.file = file;
}
@Override
public void run() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException ex) {
throw new IllegalStateException("bf4logreader.Reader.run: File has not been found. file = " + file);
}
while (isReading) {
String line = null;
try {
line = reader.readLine();
} catch (IOException ex) {
throw new IllegalStateException("bf4logreader.Reader.run: Something went wrong when reading file. file = " + file);
}
if (line == null) {
//No new lines
long startSleepTime = System.currentTimeMillis();
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException ex) {
if (isReading) {
//Not supposed to be interrupted
Thread.sleep(System.currentTimeMillis() - startSleepTime);
}
else {
try {
//Needs to shutdown
reader.close();
} catch (IOException ex1) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}
else {
//Process new lines
System.out.println("Line: " + line);
}
}
}
public void shutdown() {
isReading = false;
}
}
我认为很聪明,如果线程被不适当地中断,它仍然必须休眠的时间让线程处于休眠状态。但是我当然不能在这个派系中这样做,因为它需要再次处理Thread.sleep
's 。InterrruptedException
我认为它需要转换为某个while
循环,但我该怎么做呢?
编辑:对不起,我忘了把这个程序背后的想法。但我想实时监控一个日志文件,所以它永远不会停止读取该文件,除非我用关闭消息表示。