安卓 - 只读文件系统 IOException

20

我正在尝试在Android系统上写入一个简单的文本文件。这是我的代码:

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: open failed: EROFS (Read-only file system)"错误。我已经尝试添加以下权限到我的Manifest文件中,但没有成功:

<?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" />

有人知道问题出在哪里吗?

2个回答

87
因为您尝试将文件写入根目录,所以需要将文件路径传递给您的文件目录。
示例
String filePath = context.getFilesDir().getPath().toString() + "/fileName.txt";
File f = new File(filePath);

3

请尝试使用开发者指南中文章中的方法:

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

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

这对我有用,但我正在处理字符串。有没有办法使用FileOutputStream来写入字符串而不是字节? - John Roberts
1
他所输入的是一个字符串的写法,只是该字符串的字节表示。当您在文本编辑器中查看文件或将其读回(作为字符串),您将获得您编写内容的字符串表示形式。 - Jug6ernaut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接