我目前正在开发一个控制台应用程序,它使用Java 7 WatchService API观察多个目录。
在主要方法中观察循环发生时,我想要一个单独的线程从System.in
流中读取以检查观察是否必须停止。
我的Runnable
实现如下:
public class InputHandler implements Runnable {
@Override
public void run() {
boolean keepRunning = true;
int readBytes = -1;
byte[] readChunk = new byte[8];
System.out.println("Starting directory observation ...");
System.out.println("Type 'stop' to end directory observation.\n");
while (keepRunning) {
try {
readBytes = System.in.read(readChunk);
if (readBytes > 4) {
keepRunning &= !(new String(readChunk).contains("stop"));
}
} catch (Exception e) {
System.err.println("Failed to read input!");
keepRunning = false;
}
}
System.out.println("\nDirectory observation stops now ...");
}
}
我的主要方法是:
// Prepare the WatchService stuff ...
Thread ihThread = new Thread(new InputHandler());
do {
WatchKey watchKey = directoryWatch.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
// do something
}
}
keepRunning &= !Thread.State.TERMINATED.equals(ihThread.getState())
&& watchKey.reset();
} while (keepRunning);
当我运行代码时,没有打印任何消息,我无法在命令行中写任何内容。如何从新主题访问“主要”System.in
和System.out
?