<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Java `WatchService` API 教程 > 原文: [https://howtodoinjava.com/java8/java-8-watchservice-api-tutorial/](https://howtodoinjava.com/java8/java-8-watchservice-api-tutorial/) 在此示例中,我們將學習使用 Java 8 `WatchService` API 觀察目錄及其中的所有子目錄和文件。 ## 如何注冊 Java 8 `WatchService` 要注冊`WatchService`,請獲取目錄路徑并使用`path.register()`方法。 ```java Path path = Paths.get("."); WatchService watchService = path.getFileSystem().newWatchService(); path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); ``` ## 觀察變化事件 要獲取目錄及其中文件的更改,請使用`watchKey.pollEvents()`方法以流的形式返回所有更改事件的集合。 ```java WatchKey watchKey = null; while (true) { watchKey = watchService.poll(10, TimeUnit.MINUTES); if(watchKey != null) { watchKey.pollEvents().stream().forEach(event -> System.out.println(event.context())); } watchKey.reset(); } ``` 該密鑰一直有效,直到: * 通過調用其`cancel`方法顯式地取消它,或者 * 隱式取消,因為該對象不再可訪問,或者 * 通過關閉觀察服務。 如果您要重復使用同一鍵在一個循環中多次獲取更改事件,請不要忘記調用`watchKey.reset()`方法,該方法會將鍵再次設置為**就緒**狀態。 > 請注意,諸如如何檢測事件,其及時性以及是否保留其順序之類的幾件事高度依賴于底層操作系統。 某些更改可能導致一個操作系統中的單個條目,而類似的更改可能導致另一操作系統中的多個事件。 ## 監視目錄,子目錄和文件中的更改示例 在此示例中,我們將看到一個觀看目錄的示例,該目錄中包含所有子目錄和文件。 我們將維護監視鍵和目錄`Map<WatchKey, Path> keys`的映射,以正確識別已修改的目錄。 下面的方法將向觀察者注冊一個目錄,然后將目錄和密鑰存儲在映射中。 ```java private void registerDirectory(Path dir) throws IOException { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); keys.put(key, dir); } ``` 在遍歷目錄結構并為遇到的每個目錄調用此方法時,將遞歸調用此方法。 ```java private void walkAndRegisterDirectories(final Path start) throws IOException { // register directory and sub-directories Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { registerDirectory(dir); return FileVisitResult.CONTINUE; } }); } ``` 請注意,無論何時創建新目錄,我們都會在觀察服務中注冊該目錄,并將新密鑰添加到映射中。 ```java WatchEvent.Kind kind = event.kind(); if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(child)) { walkAndRegisterDirectories(child); } } catch (IOException x) { // do something useful } } ``` 將以上所有內容與處理事件的邏輯放在一起,完整的示例如下所示: ```java package com.howtodoinjava.examples; import static java.nio.file.StandardWatchEventKinds.*; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map; public class Java8WatchServiceExample { private final WatchService watcher; private final Map<WatchKey, Path> keys; /** * Creates a WatchService and registers the given directory */ Java8WatchServiceExample(Path dir) throws IOException { this.watcher = FileSystems.getDefault().newWatchService(); this.keys = new HashMap<WatchKey, Path>(); walkAndRegisterDirectories(dir); } /** * Register the given directory with the WatchService; This function will be called by FileVisitor */ private void registerDirectory(Path dir) throws IOException { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); keys.put(key, dir); } /** * Register the given directory, and all its sub-directories, with the WatchService. */ private void walkAndRegisterDirectories(final Path start) throws IOException { // register directory and sub-directories Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { registerDirectory(dir); return FileVisitResult.CONTINUE; } }); } /** * Process all events for keys queued to the watcher */ void processEvents() { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { @SuppressWarnings("rawtypes") WatchEvent.Kind kind = event.kind(); // Context for directory entry event is the file name of entry @SuppressWarnings("unchecked") Path name = ((WatchEvent<Path>)event).context(); Path child = dir.resolve(name); // print out event System.out.format("%s: %s\n", event.kind().name(), child); // if directory is created, and watching recursively, then register it and its sub-directories if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(child)) { walkAndRegisterDirectories(child); } } catch (IOException x) { // do something useful } } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } } public static void main(String[] args) throws IOException { Path dir = Paths.get("c:/temp"); new Java8WatchServiceExample(dir).processEvents(); } } ``` 運行該程序并在給定輸入中更改文件和目錄后,您將在控制臺中注意到捕獲的事件。 ```java Output: ENTRY_CREATE: c:\temp\New folder ENTRY_DELETE: c:\temp\New folder ENTRY_CREATE: c:\temp\data ENTRY_CREATE: c:\temp\data\New Text Document.txt ENTRY_MODIFY: c:\temp\data ENTRY_DELETE: c:\temp\data\New Text Document.txt ENTRY_CREATE: c:\temp\data\tempFile.txt ENTRY_MODIFY: c:\temp\data ENTRY_MODIFY: c:\temp\data\tempFile.txt ENTRY_MODIFY: c:\temp\data\tempFile.txt ENTRY_MODIFY: c:\temp\data\tempFile.txt ``` 這就是使用 Java 8 `WatchService` API 監視文件更改并進行處理的簡單示例。 學習愉快! 資源: [`WatchService` Java 文檔](https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html) [遍歷文件樹](https://docs.oracle.com/javase/tutorial/essential/io/walk.html) [Java 8 路徑](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html) [Lambda 表達式](https://en.wikipedia.org/wiki/Lambda)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看