Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Read Only File System IOException

Tags:

I am trying to write to a simple text file on the Android system. This is my code:

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();
       }

However, this code produces a "java.io.IOException: open failed: EROFS (Read-only file system)" error. I have tried adding permissions to my Manifest file as follows with no success:

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

Anyone have any idea what the problem is?

like image 222
John Roberts Avatar asked May 28 '12 16:05

John Roberts


2 Answers

Because you are trying to write the file to root, you need to pass the file path to your file directory.

Example

String filePath = context.getFilesDir().getPath().toString() + "/fileName.txt";
File f = new File(filePath);
like image 155
Jug6ernaut Avatar answered Sep 27 '22 20:09

Jug6ernaut


Try to use the approach from this article in developer guide:

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

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
like image 20
Andrey Ermakov Avatar answered Sep 27 '22 22:09

Andrey Ermakov