2014-12-02 75 views
0

我需要在android中實現一個服務,必須能夠監視文件夾以檢測某個文件並閱讀它包含的內容。我的代碼有一個奇怪的行爲,我找不到原因。這是我的相關代碼。Android服務文件觀察員奇怪的行爲

public void onCreate(){ 
    lectorFichCSV = new LectorFichCSV(); //object to read CSV files  
    ftpFileObserver = new FileObserver(filePath.getAbsolutePath()){ 
     public void onEvent(int event, String file) { 
      if((FileObserver.CREATE & event) != 0){ 
       Log.i("INFO: ", filePath.getAbsolutePath() + "/" + file + " is created"); 
       if(file.substring(0,3).equals("RVE")){ //If file is created and the one I expect 
        try{ 
         Log.i("INFO: ", "We have a RVE answer"); 
         is = new FileInputStream(filePath + "/" + file); 
         lineaVent = lectorFichCSV.parseCSVFileAsList(is); //Get information in a list 
         //Get dao from ORMLite 
         dao = getHelper().getLineaVentDao(); 
         Iterator<String[]> iterator = lineaVent.iterator(); 
         if(iterator.hasNext()){ 
          String[] aux = iterator.next(); 
          Log.i("INFO:", "CodLineaVent "+aux[0]); 
          if(aux[2].equals("S")){ 
           //Update DB information accordin to my file 
           UpdateBuilder<LineaVent, Integer> updateBuilder = dao.updateBuilder(); 
           updateBuilder.where().eq("_id", aux[0]); 
           updateBuilder.updateColumnValue("valido", true); 
           updateBuilder.updateColumnValue("saldo", true); 
           updateBuilder.update(); 
           lineaVent.clear(); 
          }else if(aux[2].equals("N")){ 
           UpdateBuilder<LineaVent, Integer> updateBuilder = dao.updateBuilder(); 
           updateBuilder.where().eq("_id", aux[0]); 
           updateBuilder.updateColumnValue("saldo", false); 
           updateBuilder.update(); 
           lineaVent.clear(); 
          } 
          File fileToDel = new File(filePath + "/" + file); 
          fileToDel.delete(); 
         } 
        }catch(FileNotFoundException e){ 
         e.printStackTrace(); 
        }catch(SQLException e){ 
         e.printStackTrace(); 
        } 
       } 

我調試的代碼,有時是工作,有時我得到lineaVent.size()== 0,我要瘋了這一點,我在想,有沒有可能發生的事件比快創建我的文件?這是當我試圖解析我的CSV文件到我的List對象是size = 0的原因嗎?在這種情況下,我沒有得到任何FileNotFoundException。 任何幫助將不勝感激。謝謝。

+0

從閱讀[FileObserver'的JavaDocs](https://developer.android.com/reference/android/os/FileObserver.html),我期望對於一個新文件,我會得到一個CREATE '事件,零個或多個'MODIFY'事件和一個'CLOSE_WRITE'事件。看看你得到什麼事件,如果你看到一個'CLOSE_WRITE',你應該延遲你的工作,直到事件發生。 – CommonsWare 2014-12-02 12:21:06

+0

所以問題在於事件發生,我嘗試讀取文件,它仍然是空的?我是否必須嵌套另一個如果在CLOSE_WRITE之內,然後閱讀它? – acostela 2014-12-02 12:24:54

+0

「所以問題是發生了事件,我嘗試讀取文件,它仍然是空的?」 - 這是我的猜測,是的。 「我必須嵌套另一個如果在CLOSE_WRITE的內部,然後閱讀它?」 - 我無法真正回答這個問題,因爲這是你的應用程序,不是我的。 – CommonsWare 2014-12-02 12:25:53

回答

1

我不是inotify POSIX API的專家,IIRC是FileObserver的基礎。但是,考慮到CREATE,MODIFYCLOSE_WRITE存在單獨事件,因此CREATE事件僅用於文件創建 - 換句話說,爲文件在文件系統中分配新條目是有原因的。這可能會創建一個空文件,也可能是一個初始負載爲字節的文件,但可能需要調用其他MODIFY來寫出全部內容。 CLOSE_WRITE然後將被調用以指示誰正在寫入文件的人現在已經關閉了他們的文件句柄。

因此,如果你正在看的要創建一些文件,讀取它,觀看CREATE,然後查看CLOSE_WRITE對同一個文件,然後嘗試讀取它,看看是否能更好地工作。