三、當然也可以藉由Mavan套件管理程式來下載,xml如下:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
四、首先建立一個類,名為FileListenerAdaptor並實作FileAlterationListener這個介面。
public class FileListenerAdaptor implements FileAlterationListener{
@Override
public void onStart(FileAlterationObserver fileAlterationObserver) {
}
@Override
public void onDirectoryCreate(File file) {
}
@Override
public void onDirectoryChange(File file) {
}
@Override
public void onDirectoryDelete(File file) {
}
@Override
public void onFileCreate(File file) {
}
@Override
public void onFileChange(File file) {
}
@Override
public void onFileDelete(File file) {
}
@Override
public void onStop(FileAlterationObserver fileAlterationObserver) {
}
}
五、上面包含了目錄創建、改變、刪除,檔案創建、改變、刪除,這幾個方法,也就是說我們可以在這裡撰寫當這些動作發生時要做什麼事,舉例來說,當一個檔案備建立時,需印出檔案的長度、修改日期、操作權限等,那麼就在onFileCreate寫下這些代碼:
@Override
public void onFileCreate(File file) {
System.out.println(file.getAbsoluteFile() + " was created.");
System.out.println("----------> length: " + file.length());
System.out.println("----------> last modified: " + new Date(file.lastModified()));
System.out.println("----------> readable: " + file.canRead());
System.out.println("----------> writable: " + file.canWrite());
System.out.println("----------> executable: " + file.canExecute());
}
六、接著實際來使用:
final File directory = new File("C:\\Users\\will\\Downloads");
FileAlterationObserver fao = new FileAlterationObserver(directory);
fao.addListener(new FileListenerAdaptor());
final FileAlterationMonitor monitor = new FileAlterationMonitor();
monitor.addObserver(fao);
try {
monitor.start();
} catch (Exception e) {
e.printStackTrace();
}
七、執行結果:
開始監聽
C:\Users\Administrator\Downloads\rubyinstaller-2.1.5 - 複製 - 複製.exe was created.
----------> length: 17568211
----------> last modified: Sun Jan 11 22:02:25 CST 2015
----------> readable: true
----------> writable: true
----------> executable: true
八、若要指定時間進行尋訪的話那麼在new FileAlterationMonitor時可以加入參數,其建構子接受interval這個參數
final FileAlterationMonitor monitor = new FileAlterationMonitor(500);
留言
張貼留言