2013-06-25 36 views
0

我正在製作一個服務,使用穩定的RecursiveFileObserver觀看文件的讀數變化,這個文件觀察者將被分配觀察文件修改(FileObserver.MODIFY)...我想要這個觀察者onEvent是將文件的值更改爲它在更改之前的值。所以週期爲:閱讀/獲取文件的讀數,然後它發生變化

服務啓動和觀察者startsWatching - >文件由X更改 - >我的觀察者將此更改爲任何它在被X更改之前...

所以我需要的是一種方法來讀取文件的值在被X更改之前的值。

那麼有人可以幫助我嗎?甚至有可能嗎?

這是什麼,我試圖做的一個片段:

@Override 
    public void onEvent(int event, String path) { 
     // TODO Auto-generated method stub 
     super.onEvent(event, path); 

     if(event != MODIFY){ 
      return; 
     } 

     if (CoresManagement.isAccessAllowed()){ //If the access is allowed , doesn't do anything ...   
      return; 
     } 

     //Here is where I want to do what I said above 

      if (path == "le Wild Location"){ 
       modifyFile("le Wild Location" , "Here is the value I want to know , the old value "); 
      } 

請,如果你發現什麼不清楚的地方,我可以解釋!

回答

0

你可以做什麼它implementa一個FileObserver

fileObserver =新FileObserver(pathOfFile){

@Override 
public void onEvent(int event, String file) { 
    // on any change in the file you can replace the old file. 
    //basically keep the backup file some where or in the buffer and replace with this file if there is any change. 
} 
}; 
fileObserver.startWatching(); 

替換文件。

FileChannel origFile = null; 
FileChannel modFile = null; 
long cnt = 0; 
long size = 0; 

try { 
    origFile = new FileInputStream(sourceFile).getChannel(); 
    modFile = new FileOutputStream(destFile).getChannel(); 

    size = origFile.size();    
    while((cnt += modFile.transferFrom(origFile, cnt, size-cnt))<size); 
} 
finally { 
    if(origFile != null) { 
     origFile.close(); 
    } 
    if(modFile != null) { 
     modFile.close(); 
    } 
} 
+0

這就是我正在做的,但是這樣做的全部目的是我希望我的應用程序更改此文件,同時限制其他人(包括系統)更改它...此過程用於限制部分這個過程,因爲你看到了'if(CoresManagement.isAccessAllowed()'),一旦我的應用程序試圖改變文件,允許訪問,在完成之後,它不允許它......並且我的意思是不允許,我的意思是將文件更改爲任何人更改之前的文件,爲此,我需要以某種方式讀取文件,然後才能更改 – Seaskyways

+0

您可以創建私人文件嗎? 您可以使用openFileOutput(「filename」,MODE_PRIVATE)方法 – blganesh101

+0

我正在更改的文件是在/ sys目錄下,只有root和system可以更改它,因此,對於使用經典shell命令(su,回聲,貓....)...所以沒有 – Seaskyways