I'm using FileObserver to monitor changes in folders.
Events are triggered as expected but I have problem making a distinction between Files and Directories in the events DELETE
and MOVED_FROM
, since after the event is triggered, calling both File.isFile()
and File.isDirectory()
is false (which make sense).
Is there an efficient way to make this check before file is removed? I do have a workaround by listing all files in effected folder, however it's inefficient.
Fileobserver code:
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;
}
}
};
EDIT:
This is how is File/Folder is evaluated in 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");
}
And the relevant logcat output is:
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