Android Checking if the file size exceeded a certain value

Is it possible to set the listener in the created file and warn when the file size has reached a certain value.

+5
source share
3 answers

Yes and no. There is a class called FileObserver that allows you to listen to certain events, such as when a file opens, closes, or changes. There is no special listener for file size, but MODIFY or CLOSE_WRITE -event is suitable.

See documentation: http://developer.android.com/reference/android/os/FileObserver.html

A brief example:

 observer = new FileObserver(pathToFile,MODIFY + CLOSE_WRITE) @Override public void onEvent(int event, String file) { Log.d(TAG, "File changed[" + pathToWatch + file + "]"); //TODO: check file size... } }; observer.startWatching(); 
+3
source

You can check file size changes as follows.

  • Save the current file size in settings or in another storage location
  • create file listener
  • whenever it starts, compare file size with pre-saved size

 curFileSize = fileObject.length(); //size should be stored // creating listener fileObserver = new FileObserver(pathToFile,MODIFY + CLOSE_WRITE) @Override public void onEvent(int event, String file) { //checking size if(curFileSize != fileObject.length()) { //there is some change } } }; observer.startWatching(); 
0
source
  double bytes = fileobj.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); // you can find File size like above.... //if you are Writing a file via output writer you can also check in between file writing Process....that file writer reached at certain Size !!! 
-2
source

All Articles