上一个文章监听文件时java自带的,本文的文件监听代码是apache第三方的文件监听。用此包需要引入第三方。通过类直接可以调用本代码的静态方法
代码如下:
package com.demo.filelistener;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import android.os.Environment;
public class MonitorFile {
/* 文件 */
public static void monitorFile() {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
try {
String path = "文件路径";
File filPath = new File(path);
// 账单
if (!filPath.exists()) {
filPath.mkdirs();
}
new Thread() {
//监听事件
long t= TimeUnit.MILLISECONDS.toMillis(500);
String path = "文件路径";
public void run() {
try {
//文件观察者,第一个参数是文件路径,第二个是实现FileFilter的类。通过FileAlterationMonitor 类引用开启监听
FileAlterationObserver observer = new FileAlterationObserver(
new File(path), new FileFilterImpl());
FileAlterationMonitor monitor = new FileAlterationMonitor(
t,new FileAlterationObserver[] { observer });
monitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
demo2:
import java.io.File;
import java.io.FileFilter;
import android.content.Context;
public class FileFilterImpl implements FileFilter {
private Context context =GabelApplication.getInstance() ;
private SharepreferenceData sharepreferenceData = SharepreferenceData
.getInstance(context);
private byte[] lock = new byte[0];
@Override
public boolean accept(File pathname) {
//处理想要实现的代码
return false;
}
}
public class GabelApplication extends Application {
private static GabelApplication instance;
public static GabelApplication getInstance() {
if (instance == null) {
instance = new GabelApplication();
}
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}