我正在使用 FileObserver 来监视文件夹中的更改。
事件按预期触发,但我在区分事件中的文件和目录时遇到问题,因为在触发事件DELETE
后MOVED_FROM
,调用两者File.isFile()
和File.isDirectory()
是错误的(这是有道理的)。
在删除文件之前是否有有效的方法进行此检查?通过列出受影响文件夹中的所有文件,我确实有一个解决方法,但是它效率低下。
文件观察器代码:
mFileObserver = new FileObserver(DIRECTORY.getPath()) {
@Override
public void onEvent(int event, String path) {
event &= FileObserver.ALL_EVENTS;
switch (event) {
case (CREATE):
case (MOVED_TO):
Log.d(TAG, "Added to folder: " + DIRECTORY + " --> File name " + path);
addChild(path);
break;
case (DELETE):
case (MOVED_FROM):
Log.d(TAG, "Removed from folder " + DIRECTORY + " --> File name " + path);
removeChild(path);
break;
case (MOVE_SELF):
case (DELETE_SELF):
removeDirectory();
break;
}
}
};
编辑:
这就是文件/文件夹的评估方式removeChild(String)
private void removeChild(String name) {
mFileObserver.stopWatching();
String filepath = this.getAbsolutePath() + separator + name;
File file = new File(filepath);
if (file.exists())
Log.d(TAG, "Exists");
else Log.d(TAG, " Does not Exists");
if (file.isDirectory())
Log.d(TAG, "is Directory");
else Log.d(TAG, " is NOT Directory");
if (file.isFile())
Log.d(TAG, "is File");
else Log.d(TAG, " is NOT File");
}
相关的logcat输出是:
04-03 12:37:20.714 5819-6352: Removed from folder /storage/emulated/0/Pictures/GR --> File name ic_alarm_white_24dp.png
04-03 12:37:20.714 5819-6352: Does not Exists
04-03 12:37:20.714 5819-6352: is NOT Directory
04-03 12:37:20.714 5819-6352: is NOT File