实时监测文件夹中新增的文件和文件夹(java)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1.通过Apache的包进行文件监测

实例代码如下:

// 个人更推荐用Apache的包,这台机器没有Apache的lib,就做了一个JDK的。
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
 
public class FileMonitor {
 
    public static void main(String[] args) throws Exception {
        String filePath = "D:\\hlsXML\\";
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Paths.get(filePath).register(watchService,
            StandardWatchEventKinds.ENTRY_CREATE);
 
        while (true) {
            WatchKey key = watchService.take();
            for (WatchEvent event : key.pollEvents()) {
               // System.out.println(event.context() + "  " + event.kind());
                String fileName = "D:\\hlsXML\\"+event.context();
                //System.gc();
                OutputXmlDemo.parserXml(fileName);
            }
            if (!key.reset()) {
                break;
            }
        }
    }
 
}

预览效果;

实时监测文件夹中新增的文件和文件夹(java)_第1张图片

转载于:https://my.oschina.net/liusonghuang/blog/1476359

你可能感兴趣的:(实时监测文件夹中新增的文件和文件夹(java))