2012-05-28 109 views
11

我正在嘗試寫入Android系統上的簡單文本文件。這是我的代碼:Android - 只讀文件系統IOException

public void writeClassName() throws IOException{ 
    String FILENAME = "classNames"; 
    EditText editText = (EditText) findViewById(R.id.className); 
    String className = editText.getText().toString(); 

    File logFile = new File("classNames.txt"); 
     if (!logFile.exists()) 
     { 
      try 
      { 
      logFile.createNewFile(); 
      } 
      catch (IOException e) 
      { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
     } 
     try 
     { 
      //BufferedWriter for performance, true to set append to file flag 
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(className); 
      buf.newLine(); 
      buf.close(); 
     } 
     catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

但是,此代碼產生了「java.io.IOException異常:打開失敗:EROFS(只讀文件系統)」的錯誤。我曾嘗試添加權限到我的清單文件如下,但沒有成功:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="hellolistview.com" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk android:minSdkVersion="15" /> 

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 
    <activity 
     android:name=".ClassView" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <activity 
     android:name=".AddNewClassView" 
     /> 

</application> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

任何人有任何的想法是什麼問題?

回答

57

由於您試圖將文件寫入根目錄,因此需要將文件路徑傳遞到文件目錄。

String filePath = context.getFilesDir().getPath().toString() + "/fileName.txt"; 
File f = new File(filePath); 
+0

這爲我工作。謝謝。 –

2

嘗試使用此article的做法,開發人員指南:

String FILENAME = "hello_file"; 
String string = "hello world!"; 

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
fos.write(string.getBytes()); 
fos.close(); 
+0

這適用於我,但我正在處理字符串。無論如何,使用FileOutputStream來寫字符串而不是字節? –

+1

他所寫的是一個字符串,只是字符串的字節表示形式。當您在文本編輯器中查看該文件或將其讀回(以字符串形式)時,您將獲得所寫的w/e的字符串表示。 – Jug6ernaut

相關問題