我使用 org.apache.commons.io.monitor.FileAlterationMonitor 创建了一个文件观察器。文件更改被正确捕获。但我想使用单独的方法停止监视任务。它不工作。源代码如下。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.io.monitor.FileEntry;
public class FileMonitor2 {
//public final class FileMonitorExample {
private static final String EXAMPLE_PATH =
"D:\\testrail\\install.txt";
private static final String PARENT_DIR1 =
"D:\\ibi\\DevStudio77\\client\\wfc\\etc";
private static final String PARENT_DIR2 =
"D:\\ibi\\DevStudio77\\config";
public static void runExample(boolean b) {
System.out.println("File Monitor example...");
FileAlterationMonitor monitor=new FileAlterationMonitor();
// FileEntry
// We can monitor changes and get information about files
// using the methods of this class.
if(b){
FileEntry entry = new FileEntry(FileUtils.getFile(EXAMPLE_PATH));
System.out.println("File monitored: " + entry.getFile());
System.out.println("File name: " + entry.getName());
System.out.println("Is the file a directory?: " + entry.isDirectory());
// File Monitoring
// Create a new observer for the folder and add a listener
// that will handle the events in a specific directory and take action.
File parentDir = FileUtils.getFile(PARENT_DIR1);
FileAlterationObserver observer = new FileAlterationObserver(parentDir);
observer.addListener(new FLA2());
File parentDir1 = FileUtils.getFile(PARENT_DIR2);
FileAlterationObserver observer2 = new FileAlterationObserver(parentDir1);
// observer.addListener(new FLA());
observer2.addListener(new FLA());
// Add a monior that will check for events every x ms,
// and attach all the different observers that we want.
monitor.addObserver(observer);
//monitor = new FileAlterationMonitor(500, observer);
monitor.addObserver(observer2);
try {
monitor.start();
System.out.println("Started");
// After we attached the monitor, we can create some files and directories
// and see what happens!
//monitor.stop();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}else{
/*System.out.println("type the value");
Scanner sc=new Scanner(System.in);
String ss=sc.next();
if(ss.equals("aa")){*/
try {
monitor.stop();
System.out.println("stopped");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// }
}
}
public static void main(String args[]) throws InterruptedException{
runExample(true);
System.out.println("After start");
Thread.sleep(1000);
runExample(false);
}
//}
}