【问题标题】:Restart Thread with watching folder使用监视文件夹重新启动线程
【发布时间】: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


【解决方案1】:

可以随时调用close 方法来关闭服务,从而导致任何线程等待检索密钥,从而抛出ClosedWatchServiceException

ClosedWatchServiceException - 如果此监视服务已关闭,或者在等待下一个键时已关闭。

在您的情况下,我认为,这只是在调用 take 并静默处理时捕获异常的问题,例如:

try {
    key = myWatcher.take()
} catch (ClosedWatchServiceException e) {
    continue;
}

这是根据: https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html

【讨论】:

  • 您是如何解决此问题的。我正在寻求类似的帮助,我想重新启动我的 Java 程序,我可以使用您使用的相同方法吗?这是我与重新启动脚本有关的问题 - stackoverflow.com/questions/66169748/... -
  • @Aldic,可以帮助解决这个问题。我正在尝试了解您的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
相关资源
最近更新 更多