-2

Java WatchEvent 检查类型??

我将检查 WatchEvent 中的路径类型,我想检查路径是 WatchEvent 中的文件或文件夹:)

我没有更多的细节......

我的 Java 源代码:

package de.R3N3PDE.DriveIO;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class DriveIO {
    static WatchService watcher;
    public static void main(String args[]){
        try {
            watcher = FileSystems.getDefault().newWatchService();
            new File("C:/Users/R3N3PDE/Desktop/Test").toPath().register(watcher,  StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        while(true){
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            for (WatchEvent<?> event: key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                WatchEvent<Path> ev = (WatchEvent<Path>)event;
                Path filename = ev.context().toAbsolutePath();
                if(filename.toFile().isDirectory()){
                    System.out.println("Is Dir");
                }else{
                    System.out.println("Is File");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    }
}
4

1 回答 1

1

你可以java.nio.file.Files.isDirectory(Path path)用来测试你是否Path是一个目录。

于 2013-07-28T06:54:29.440 回答