Android检查文件大小是否超过某个值

时间:2015-07-02 12:09:53

标签: java android

是否可以在创建的文件上设置侦听器,并在文件大小达到某个值时发出警报。

3 个答案:

答案 0 :(得分:3)

是和否。 有一个名为FileObserver的类,它允许您侦听某些事件,例如在打开,关闭或修改文件时。文件大小没有特定的侦听器,但MODIFYCLOSE_WRITE - 事件都适合。

查看文档:{​​{3}}

简短的例子:

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();

答案 1 :(得分:0)

您可以按如下方式检查文件大小更改。

  1. 在首选项或其他存储位置保存当前文件大小
  2. 创建文件的监听器
  3. 每当触发时,将文件大小与预先存储的大小进行比较
  4. 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();
    

答案 2 :(得分:-2)

      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 !!!