java7 WatchService 您用过吗?

每当这些文件发生任何更改时,它们都会自动刷新 -这是大多数应用程序中常见的非常普遍的问题。每个应用程序都有一些配置,预期该配置文件中的每次更改都会刷新。解决该问题的过去方法包括使用Thread,根据配置文件的“ 最后更新时间戳 ” 定期轮询文件更改。
现在使用Java 7,情况已经改变。Java 7引入了一项出色的功能:WatchService。我将尽力为您解决上述问题。这可能不是最好的实现,但是肯定会为您的解决方案提供一个很好的开始。我敢打赌!

1.Java WatchService API

A WatchService是JDK的内部服务,它监视注册对象的更改。这些注册的对象必须是Watchable接口的实例。在向中注册可监视实例时WatchService,我们需要指定我们感兴趣的变更事件的类型。
到目前为止,有四种类型的事件:

  1. ENTRY_CREATE,
  2. ENTRY_DELETE,
  3. ENTRY_MODIFY, and
  4. OVERFLOW.

WatchServiceinterface扩展了Closeable接口,表示可以在需要时关闭服务。通常,应该使用JVM提供的关闭挂钩来完成。

2.应用程序配置提供程序

配置提供程序只是用于包装java,util.Properties实例中的属性集的包装器。它还提供了使用KEY来获取配置属性的方法。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class ApplicationConfiguration {
    private final static ApplicationConfiguration INSTANCE = new ApplicationConfiguration();
 
    public static ApplicationConfiguration getInstance() {
        return INSTANCE;
    }
 
    private static Properties configuration = new Properties();
 
    private static Properties getConfiguration() {
        return configuration;
    }
 
    public void initilize(final String file) {
        InputStream in = null;
        try {
            in = new FileInputStream(new File(file));
            configuration.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public String getConfiguration(final String key) {
        return (String) getConfiguration().get(key);
    }
 
    public String getConfigurationWithDefaultValue(final String key,
            final String defaultValue) {
        return (String) getConfiguration().getProperty(key, defaultValue);
    }
}

3.配置更改侦听器– File Watcher

现在,当我们有了配置属性的内存中高速缓存的基本包装器时,我们需要一种机制,只要存储在文件系统中的配置文件发生更改,就可以在运行时重新加载此高速缓存。
我已经写了一个示例工作代码来为您提供帮助:

 
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
 
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
 
public class ConfigurationChangeListner implements Runnable {
    private String configFileName = null;
    private String fullFilePath = null;
 
    public ConfigurationChangeListner(final String filePath) {
        this.fullFilePath = filePath;
    }
 
    public void run() {
        try {
            register(this.fullFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private void register(final String file) throws IOException {
        final int lastIndex = file.lastIndexOf("/");
        String dirPath = file.substring(0, lastIndex + 1);
        String fileName = file.substring(lastIndex + 1, file.length());
        this.configFileName = fileName;
 
        configurationChanged(file);
        startWatcher(dirPath, fileName);
    }
 
    private void startWatcher(String dirPath, String file) throws IOException {
        final WatchService watchService = FileSystems.getDefault()
                .newWatchService();
        Path path = Paths.get(dirPath);
        path.register(watchService, ENTRY_MODIFY);
 
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    watchService.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
 
        WatchKey key = null;
        while (true) {
            try {
                key = watchService.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    if (event.context().toString().equals(configFileName)) {
                        configurationChanged(dirPath + file);
                    }
                }
                boolean reset = key.reset();
                if (!reset) {
                    System.out.println("Could not reset the watch key.");
                    break;
                }
            } catch (Exception e) {
                System.out.println("InterruptedException: " + e.getMessage());
            }
        }
    }
 
    public void configurationChanged(final String file) {
        System.out.println("Refreshing the configuration.");
        ApplicationConfiguration.getInstance().initilize(file);
    }
}

上面的类是使用线程创建的,该线程将使用侦听配置属性文件的更改WatchService
一旦检测到文件中的任何修改,它便会刷新配置中的内存缓存。
上述侦听器的构造函数仅采用一个参数,即受监视的配置文件的标准路径。Listener在文件系统中更改配置文件时,将立即通知类。
然后,此侦听器类调用ApplicationConfiguration.getInstance().initilize(file);以重新加载到内存缓存中。

4.测试我们的代码

现在,当我们准备好上课时,我们将对其进行测试。
首先,将test.properties具有以下内容的'C:/Lokesh/temp'文件存储在文件夹中。

TEST_KEY = TEST_VALUE

现在,让我们使用以下代码测试以上类。

public class ConfigChangeTest {
    private static final String FILE_PATH = "C:/Lokesh/temp/test.properties";
 
    public static void main(String[] args) {
        ConfigurationChangeListner listner = new ConfigurationChangeListner(
                FILE_PATH);
        try {
            new Thread(listner).start();
            while (true) {
                Thread.sleep(2000l);
                System.out.println(ApplicationConfiguration.getInstance()
                        .getConfiguration("TEST_KEY"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
//Output of the above program (Change the TEST_VALUE to TEST_VALUE1 and TEST_VALUE2 using any file editor and save).
 
Refreshing the configuration.
 
TEST_VALUE
 
TEST_VALUE
 
TEST_VALUE
 
Refreshing the configuration.
 
TEST_VALUE1
 
Refreshing the configuration.
 
TEST_VALUE2

以上输出显示,每次我们对属性文件进行任何更改时,加载的属性都会刷新,并且可以使用新的属性值。到目前为止,已经做好了!

5.重要说明

  1. 如果在新项目中使用Java 7,并且没有在使用老式方法重新加载属性,则说明操作不正确。
  2. WatchService提供两种方法take()和poll()。在take()方法等待下一个更改发生并被阻止之前,请poll()立即检查更改事件。如果上次poll()调用没有任何变化,它将返回null。poll()方法不会阻止执行,因此应在具有一定睡眠时间的线程中调用该方法。

在评论区域中将您的问题/建议交给我。
学习愉快!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 下面是 Java 代码示例,它使用 `WatchService` 监听文件夹: ``` import java.io.IOException; import java.nio.file.*; public class FileWatcher { public static void main(String[] args) { try { WatchService watcher = FileSystems.getDefault().newWatchService(); Path dir = Paths.get("/path/to/watch"); dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); System.out.println("Watch Service registered for dir: " + dir.getFileName()); while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = ev.context(); System.out.println(kind.name() + ": " + fileName); if (kind == StandardWatchEventKinds.ENTRY_MODIFY && fileName.toString().equals("DirectoryToWatch.java")) { System.out.println("My source file has changed!!!"); } } boolean valid = key.reset(); if (!valid) { break; } } } catch (IOException ex) { System.err.println(ex); } } } ``` 该代码创建了一个 `WatchService` 实例,并将目录 `/path/to/watch` 注册为监听的目录。它将监听文件夹内的文件创建、删除和修改事件。 这是一个死循环,监听服务会在目录上等待任何事件。如果事件发生,该代码将打印事件类型(例如 `ENTRY_CREATE`)和事件上下文(即文件名)。如果事件是文件修改事件,且文件名为 `DirectoryToWatch.java`,它将打印一条信息。 请注意,该代码仅提 ### 回答2: Java提供了WatchService类来监听文件夹中的文件变化。下面是一个使用WatchService监听文件夹的示例代码: ```java import java.nio.file.*; import java.nio.file.WatchEvent.Kind; import java.nio.file.attribute.BasicFileAttributes; public class WatchServiceDemo { public static void main(String[] args) throws Exception { // 创建WatchService对象 WatchService watchService = FileSystems.getDefault().newWatchService(); // 需要监听的文件夹路径 Path dir = Paths.get("/path/to/directory"); // 注册监听事件,这里我们监听文件的创建、修改和删除事件 dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); // 启动一个线程来处理文件变化事件 Thread thread = new Thread(() -> { try { while (true) { // 获取下一个文件变化事件 WatchKey key = watchService.take(); // 遍历文件变化事件 for (WatchEvent<?> event : key.pollEvents()) { // 获取事件类型 Kind<?> kind = event.kind(); // 获取事件发生的文件路径 Path file = (Path) event.context(); // 打印事件类型和文件路径 System.out.println(kind + ": " + file); } // 重置WatchKey,否则下一次将无法接收到文件变化事件 key.reset(); } } catch (Exception e) { e.printStackTrace(); } }); // 启动文件监听线程 thread.start(); // 等待线程结束 thread.join(); } } ``` 上述代码中,我们首先创建了一个WatchService对象。然后,通过调用register方法将需要监听的文件夹路径和要监听的事件类型注册到WatchService中。在我们的例子中,我们监听了文件的创建、修改和删除事件。 接下来,我们创建一个新的线程来处理文件变化事件。在这个线程中,我们通过调用take方法获取下一个文件变化事件的WatchKey对象。然后通过遍历WatchKey的pollEvents方法获取每个事件的类型和文件路径,并输出到控制台。最后,我们重置WatchKey,以便下一次接收文件变化事件。 最后,我们启动文件监听线程,并等待线程结束。 这样,就完成了使用WatchService类来监听文件夹的代码。当文件夹中的文件发生变化时,代码将会输出对应的事件类型和文件路径。 ### 回答3: 使用JavaWatchService类可以方便地在文件夹中进行文件和目录的监视。下面是一个简单的Java代码示例,演示如何使用WatchService来监听文件夹: ```java import java.io.IOException; import java.nio.file.*; public class FolderWatcher { public static void main(String[] args) { try { // 创建WatchService对象 WatchService watchService = FileSystems.getDefault().newWatchService(); // 注册要监听的文件夹 Path folderPath = Paths.get("/path/to/folder"); folderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); System.out.println("开始监听文件夹:" + folderPath); // 监听文件夹中的事件 WatchKey key; while ((key = watchService.take()) != null) { for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } // 获取发生的事件和文件路径 WatchEvent<Path> watchEvent = (WatchEvent<Path>) event; Path fileName = watchEvent.context(); // 打印事件类型和文件路径 System.out.println(kind.name() + ": " + folderPath.resolve(fileName)); } // 重置WatchKey对象,以便继续监听 boolean valid = key.reset(); if (!valid) { break; } } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 在上面的代码中,首先创建了一个WatchService对象,然后指定要监听的文件夹,并将其注册到WatchService中。接着,使用while循环来监听文件夹中的事件。在循环中,使用take()方法从WatchService获取WatchKey对象,并通过pollEvents()方法获取WatchEvent对象列表。在列表中,可以获取到事件的类型和文件路径。最后,使用reset()方法重置WatchKey对象,以便继续监听。 需要注意的是,上述代码中需要替换"/path/to/folder"为实际要监听的文件夹路径。另外,监听到的文件和目录变化将会以事件的形式进行处理,可以根据需要进行相应的逻辑操作。 希望以上的回答对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员石磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值