2011-12-10 50 views
0

我打開內部文件,並寫信給他這樣的:獲取內部文件路徑

final String NEWLINE = new String(newLine+"\n");  
FileOutputStream fOut = openFileOutput(fileName+".txt",MODE_WORLD_READABLE); 
OutputStreamWriter osw = new OutputStreamWriter(fOut); 
osw.write(NEWLINE); 

我需要一種方法來檢查,如果內部文件(文件名+「TXT」)存在。

如果不是,請將newLine寫入文件,否則將追加 newLine文件。

我想:

File file = getBaseContext().getFileStreamPath(fileName+".txt"); 
if(file.exists())... 

但我不知道內部文件路徑,它不工作。

有什麼建議嗎?

更多細節:

private void writeStringToFile(String fileName, String newLine) { 
    final String NEWLINE = new String(newLine + "\n"); 
    FileOutputStream fOut = null; 
    OutputStreamWriter osw = null; 
    try { // catches IOException below 
     File file = getFileStreamPath(fileName + ".txt"); 
     if (!file.exists()) { 
      Log.d("DAVID", "File not exist now create him"); 
      fOut = openFileOutput(fileName + ".txt", MODE_WORLD_READABLE); 
      osw = new OutputStreamWriter(fOut); 
     } else { 
      Log.d("DAVID", "File already exist"); 
      osw = new OutputStreamWriter(fOut); 
     } 
     // Write the string to the file 
     osw.append(NEWLINE); 
     // osw.write(NEWLINE); 
     // ensure that everything is really written out and close 
     osw.flush(); 
     osw.close(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } 
} 

在運行時,它是確定的第一次 - 我越來越:「文件不存在,現在他創建」來登錄 在第二次我得到致命錯誤原因由空指針。 我想這是因爲OSW得到空FOUT

osw = new OutputStreamWriter(fOut); 

但我怎麼能阻止它?

+0

請嘗試解釋您的症狀,而不是提供無意義的陳述,如「它不工作」。 FWIW,'getFileStreamPath()'應該可以正常工作,但我不會使用'getBaseContext()' - 只需在現有的'Context'上調用'getFileStreamPath()'。或者,使用'getFilesDir()'獲取'File'對象的位置,以便'openFileOutput()'寫入文件的位置。 – CommonsWare

+0

你可以在[List](http://developer.android.com/reference/java/util/List.html)中存儲你已經使用的文件名,然後查看if(list.contains(filename))'。 – Phil

回答

1

上面的代碼是如此錯誤我不得不重寫一遍:

private void apendStringToInternalFile(String fileName, String newLine) 
     throws FileNotFoundException, UnsupportedEncodingException, 
     IOException { 
    newLine = new String(newLine + "\n"); 
    FileOutputStream fOut = openFileOutput(fileName + ".txt", 
      Context.MODE_APPEND | Context.MODE_WORLD_READABLE); 
    // MODE_WORLD_READABLE is _deprecated_ 
    try { 
     // ALWAYS SPECIFY ENCODING - 
     OutputStreamWriter osw = new OutputStreamWriter(fOut, "UTF-8"); 
     BufferedWriter buffer = new BufferedWriter(osw); 
     buffer.write(newLine); 
     buffer.flush(); 
    } finally { 
     try { 
      fOut.close(); 
     } catch (IOException e) { 
      // Log this to be on the safe side - 
      e.printStackTrace(); 
     } 
    } 
} 

顯然整個問題不存在。 openFileOutput將創建文件,如果它不存在,並添加標誌Context.MODE_APPEND它將追加如果文件確實存在。自由複製