2012-05-28 113 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

相关问题