代码如下:
public class FileObserverTest extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyFileObserver mfo = new MyFileObserver(getApplicationContext().getFilesDir() + "/data.txt");
mfo.startWatching();//启动文件监听
//mfo.stopWatching();//取消文件监听
}
public class MyFileObserver extends FileObserver {
public MyFileObserver(String path) {
super(path);
}
@Override
public void onEvent(int event, String path) {
switch (event) {
case android.os.FileObserver.CREATE:
// 文件被创建
Log.d("FileObserver", "---file create---");
break;
case android.os.FileObserver.OPEN:
// 文件被打开
//Log.d("FileObserver", "---file open---");
break;
case android.os.FileObserver.ACCESS:
// 打开文件后,读文件内容操作
//Log.d("FileObserver", "---file access---");
break;
case android.os.FileObserver.MODIFY:
//文件被修改
Log.d("FileObserver", "---file MODIFY---");
break;
}
}
}
}