【发布时间】:2018-11-24 17:13:54
【问题描述】:
我有线程正在监视设置文件中设置的文件夹。如果我更改设置,我想停止线程并使用实际文件夹启动新线程以进行观看。此代码运行“正常”但收到一些错误消息。
public static void resetWatch() throws FileNotFoundException, IOException, InterruptedException {
BufferedReader setup = new BufferedReader(new FileReader(new File("setup\\setup.dat")));
String DirtoWatch = setup.readLine();
Path toWatch = Paths.get(DirtoWatch);
if(toWatch == null) {
throw new UnsupportedOperationException("Directory not found");
}
// make a new watch service that we can register interest in
// directories and files with.
myWatcher = toWatch.getFileSystem().newWatchService();
// start the file watcher thread below
fileWatcher = new Watcher(myWatcher, toWatch);
th = new Thread(fileWatcher, "FileWatcher");
th.start();
System.out.println("Monitoring " + DirtoWatch + " for changes...");
// register a file
toWatch.register(myWatcher, ENTRY_CREATE);
th.join();
}
观察者类
public class Watcher implements Runnable {
private WatchService myWatcher;
public Path path;
private WatchKey key;
public Watcher(WatchService myWatcher, Path path) {
this.myWatcher = myWatcher;
this.path = path;
}
@Override
public void run() {
String evCon;
try {
// get the first event before looping
key = myWatcher.take();
while(key != null) {
for (WatchEvent event : key.pollEvents()) {
evCon = event.context().toString();
System.out.println("New file: " + evCon);
Thread.sleep(500);
folder_changed(path.toString() + "/" + evCon);
}
key.reset();
key = myWatcher.take();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Stopping thread");
}
public void stopThread() {
try {
System.out.println("Closing the ws");
myWatcher.close();
if(key!=null) {
key.cancel();
}
Thread.currentThread().interrupt();
} catch (IOException | ClosedWatchServiceException exc) { System.out.println("Closing thread exception"); }
}
}
如果我更改设置,我会更新设置文件,然后尝试关闭观察程序并再次运行线程:
try{
fileWatcher.stopThread();
myWatcher.close();
}
catch(ClosedWatchServiceException | IOException ex) { System.out.println("Watch Service exc. "); }
try {
resetWatch();
} catch (IOException | InterruptedException ex) { System.out.println("Recall resetWatch exc. "); }
然后它“正在运行”,但我得到了指向监视键的跟随异常:
Monitoring ..path.. for changes...
Closing the ws
Monitoring ..path.. for changes...
Exception in thread "FileWatcher" java.nio.file.ClosedWatchServiceException
Recall resetWatch exc.
at sun.nio.fs.AbstractWatchService.checkOpen(AbstractWatchService.java:80)
at sun.nio.fs.AbstractWatchService.checkKey(AbstractWatchService.java:92)
at sun.nio.fs.AbstractWatchService.take(AbstractWatchService.java:119)
at jstockcheck.Watcher.run(Watcher.java:40)
at java.lang.Thread.run(Thread.java:748)
有什么建议可以避免这个错误吗?谢谢!
【问题讨论】:
-
您是如何解决此问题的。我正在寻求类似的帮助,我想重新启动我的 Java 程序,我可以使用您使用的相同方法吗?这是我关于重新启动脚本的问题 - stackoverflow.com/questions/66169748/…
标签: java multithreading key watchservice