2015-01-16 65 views
-1

我有一個文件存儲在本地設備上,如果我不重新啓動手機,我讀得非常好。當我重新啓動並讀取日誌時,新的FileReader將引發一個NPE;爲什麼?產生NPE的文件讀取器

BufferedReader br = null; 
FileReader fr = null; 
    try { 
     Log.d("DEBUG", "Before filereader"); 
     fr = new FileReader(ABS_FILENAME); 
     Log.d("DEBUG", "Before BufferedReader"); 
     br = new BufferedReader(fr); 

     String current; 

     Log.d("DEBUG", "About to read file"); 
     while((current = br.readLine()) != null) { 

     } 
    } 
    } catch (Exception e) { 
     Log.d("DEBUG", "Exception thrown: " + e.getMessage()); 
    } finally { 
     try { 
      if (fr != null) { 
       fr.close(); 
      } 
     } catch (IOException ex) { 
      Log.d("DEBUG", "Problem closing file reader"); 
     } 
    } 
    return null; 

上述代碼發生在廣播接收機中。 ABS_FILENAME是表示文件的字符串。該文件被寫入到定期的活動,一旦遇到點:

// in an onClick that gets invoked 
try { 
      String line = myKey + " " + myValue; 
      fw.write(line); 
      fw.write(System.getProperty("line.separator")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if(fw != null) 
        fw.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

// elsewhere in the activity 
@Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my); 

    myFile = new File(getFilesDir(), FILENAME); 
    try { 
     if (!myFile.exists()) { 
      myFile.createNewFile(); 
     } 
     ABS_FILENAME = myFile.getAbsolutePath(); 
     fw = new FileWriter(myFile.getAbsoluteFile(), true); 
    } catch(IOException e) { 
    } 
+0

我認爲您發佈的代碼中存在一些語法錯誤;請修復 – Aify

+0

...不是錯誤順便說一句,它是追趕後面的額外右大括號 – Aify

+0

它是一個臨時文件,當設備重新啓動時被刪除?它是SD卡上的文件,在重新啓動後暫時無法訪問,因爲介質掃描儀正在運行? – samgak

回答

0

如果

new FileReader(ABS_FILENAME) 

真正產生NullPointerException,明確ABS_FILENAME必須爲空。