Java Apache Commons IO文件监视子文件夹中的捕获事件
我使用以下代码捕获给定文件夹中的事件。它工作正常,但我的问题是如何在给定文件夹的子文件夹中捕获事件Java Apache Commons IO文件监视子文件夹中的捕获事件,java,apache-commons,Java,Apache Commons,我使用以下代码捕获给定文件夹中的事件。它工作正常,但我的问题是如何在给定文件夹的子文件夹中捕获事件 import java.io.File; import java.io.IOException; import org.apache.commons.io.monitor.FileAlterationListener; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class Monitor {
public Monitor() {
}
//path to a folder you are monitoring .
public static final String FOLDER = MYPATH;
public static void main(String[] args) throws Exception {
System.out.println("monitoring started");
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
@Override
public void onFileCreate(File file) {
// "file" is the reference to the newly created file
System.out.println("File created: "+ file.getCanonicalPath());
}
// Is triggered when a file is deleted from the monitored folder
@Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}
我在这里读到过,这段代码也应该捕获子文件夹中的事件,但我不工作 您在代码之后对超链接所做的声明不准确。中的代码确实捕获了主/根目录和子文件夹中的某些事件(文件创建、文件删除)。它不监视文件修改或文件夹操作(创建、删除、重命名等) 我刚刚在3个级别(嵌套子文件夹)上测试了它。因此,您引用的代码实现了您的要求。如果你需要一些不同的东西,请重新措辞你的问题 如果你需要关于这个主题的更多信息,你可能会发现这个链接:有用。它确实帮助了我