commons-vfs是一个强大的虚拟文件系统,为操作各种各样的文件系统提供了统一API。这里使用的是commons-vfs2。
直接代码
package dusk;
import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
import org.junit.Test;
import java.io.File;
/**
* Created by dushangkui on 2017/4/24.
*/
public class ListenerTest {
@Test
public void test(){
try {
FileSystemManager fsm = VFS.getManager();
FileObject file = fsm.resolveFile(new File("D://vfs").getAbsolutePath());
DefaultFileMonitor fileMonitor = new DefaultFileMonitor(new FileListener() {
@Override
public void fileCreated(FileChangeEvent event) throws Exception {
resolveEvent("Created",event);
}
@Override
public void fileDeleted(FileChangeEvent event) throws Exception {
resolveEvent("Deleted",event);
}
@Override
public void fileChanged(FileChangeEvent event) throws Exception {
resolveEvent("Changed",event);
}
private void resolveEvent(String type, FileChangeEvent event){
FileObject fileObject = event.getFile();
FileName fileName = fileObject.getName();
System.out.println(type + ": " + fileName.toString());
}
});
fileMonitor.addFile(file);
fileMonitor.start();
while(true){
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
跑起来,然后在D盘下面创建vfs,并依次创建一个文本文档,重命名为ddd,打开文档编写内容并保存,删除文件,你会发现控制台会输出:
Created: file:///D:/vfs/新建文本文档.txt
Created: file:///D:/vfs/ddd.txt
Deleted: file:///D:/vfs/新建文本文档.txt
Changed: file:///D:/vfs/ddd.txt
Deleted: file:///D:/vfs/ddd.txt
做JAVA的童鞋应该都知道 java.io.File类有一个lastModified方法,它返回一个修改时间,我们也可以通过这个方法来检测文件是否被修改过。
package dusk.file;
import org.junit.Test;
import java.io.File;
/**
* Created by dushangkui on 2017/4/26.
*/
public class TestFileModified {
@Test
public void test(){
File file = new File("D:\\update.txt");
long lastModified = 0;
while(true){
if(file.lastModified()>lastModified){
lastModified=file.lastModified();
System.out.println("文件被修改, lastModified=" + lastModified);
}
}
}
}
文件被修改, lastModified=1480350296000
文件被修改, lastModified=1493190808563
文件被修改, lastModified=1493190812906