首页 > 代码库 > web工程,检测文件的变化

web工程,检测文件的变化

1.首先需要一个servlet.jar包

2.web.xml配置

<listener>
<listener-class>com.icss.MainController.FileUD</listener-class>//你的类路径
</listener>

3.具体代码

package com.icss.MainController;


import java.io.File;
import java.io.IOException;
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;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


public class FileUD implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {


}
@Override
public void contextInitialized(ServletContextEvent arg0) {
String nodepath = this.getClass().getClassLoader().getResource("/FUD").getPath().substring(1);  
System.out.println(nodepath);
WatchService ws = null;
try {
ws = FileSystems.getDefault().newWatchService();
Paths.get(nodepath).register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
} catch (IOException e) {
e.printStackTrace();
}

while (true) {
WatchKey key = null;
try {
key = ws.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(event.context() + "发生了" + event.kind() + "事件");
}
if (!key.reset()) {
break;
}
}
}
}

web工程,检测文件的变化