【问题标题】:Android - Read Only File System IOExceptionAndroid - 只读文件系统 IOException
【发布时间】:2012-06-03 00:21:52
【问题描述】:

我正在尝试在 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:打开失败: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" />

有谁知道问题出在哪里?

【问题讨论】:

    标签: java android android-emulator


    【解决方案1】:

    因为你正在尝试将文件写入根目录,所以你需要将文件路径传递给你的文件目录。

    例子

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

    【讨论】:

      【解决方案2】:

      尝试使用开发者指南中article 中的方法:

      String FILENAME = "hello_file";
      String string = "hello world!";
      
      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
      fos.write(string.getBytes());
      fos.close();
      

      【讨论】:

      • 这对我有用,但我正在处理字符串。无论如何使用 FileOutputStream 来写一个字符串而不是字节?
      • 他写的是字符串,只是字符串的字节表示。当您在文本编辑器中查看文件或将其读回(作为字符串)时,您将获得您编写的 w/e 的字符串表示形式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多