package com.test.sandbox.controller.control.export.chat; import android.os.FileObserver; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; class DirChangedListener extends FileObserver { private final static String TAG = "DirChangedListener"; public static final int MULTI_DIRS_TYPE = 0; public static final int ONE_DIR_TYPE = 1; private List<DirChangedListener> mFileObserverList = new ArrayList<DirChangedListener>(); private String mAbsolutePath; public DirChangedListener(String path, int type) { super(path); mAbsolutePath = path; if (type == MULTI_DIRS_TYPE) { setFileObserver(path); } } @Override public void onEvent(int event, String path) { final int action = event & FileObserver.ALL_EVENTS; switch (action) { case FileObserver.CREATE: android.util.Log.d(TAG, "event: create, path: " + mAbsolutePath + File.separator + path); break; } } private List<File> setFileObserver(String dir) { ArrayList<File> fileList = new ArrayList<File>(); LinkedList<File> list = new LinkedList<File>(); File fileDir = new File(dir); File file[] = fileDir.listFiles(); mFileObserverList.add(this); for (int i = 0; i < file.length; i++) { if (file[i].isDirectory()) { list.add(file[i]); DirChangedListener fileObserver = new DirChangedListener( file[i].getAbsolutePath(), DirChangedListener.ONE_DIR_TYPE); mFileObserverList.add(fileObserver); } } File tmp; while (!list.isEmpty()) { tmp = list.removeFirst(); if (tmp.isDirectory()) { DirChangedListener fileObserver = new DirChangedListener( tmp.getAbsolutePath(), DirChangedListener.ONE_DIR_TYPE); mFileObserverList.add(fileObserver); file = tmp.listFiles(); if (file == null) continue; for (int i = 0; i < file.length; i++) { if (file[i].isDirectory()) { list.add(file[i]); DirChangedListener fileObserver1 = new DirChangedListener( file[i].getAbsolutePath(), DirChangedListener.ONE_DIR_TYPE); mFileObserverList.add(fileObserver1); } } } } return fileList; } public void startDirWatch() { // TODO Auto-generated method stub for (DirChangedListener listener : mFileObserverList) { listener.startWatching(); } } public void stopDirWatch() { // TODO Auto-generated method stub for (DirChangedListener listener : mFileObserverList) { listener.stopWatching(); } } }
android 递归监控目录或者文件
最新推荐文章于 2024-04-10 16:58:53 发布