0

Hello I have a method that creates a file and writes data to it..now I want to call this method to another class to append data to that file.but when I run the app it gives me this error data.xml:open failed : EROFS (Read-only file system)

this is my method and how I call it from the first class

 String s1 = "hello";
 String s2 = "world";
 String sname = "data.xml";
 saveDataToFile(s1,s2,sname)


public void saveDataToFile(String data1, String data2 ,String fileName) {

   Log.d("Checks", "Trying to save data");



   try {
        // Set up the file directory
        String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder";
        File fileDirectory = new File(filePath);
        fileDirectory.mkdirs();
        Log.d("Checks", "Directory created");

       // Set up the file itself
        File textFile = new File(fileDirectory, fileName);
        textFile.createNewFile();
        Log.d("Checks", "File created");

       // Write to the file
        FileOutputStream fileOutputStream = new FileOutputStream(textFile);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.append(data1);
        outputStreamWriter.append(data2);
        outputStreamWriter.close();
        fileOutputStream.close();

       Toast.makeText(getApplicationContext(), "Done writing to SD card", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    } }

When I call it again I skip the set up directory and the file itself like this and I call it from the second class like this

 String s1 = "hello again";
 String s2 = "world again";
 String sname = "data.xml";
 saveDataToFile(s1,s2,sname)

public void saveDataToFile(String data1, String data2 ,String fileName) {

   Log.d("Checks", "Trying to save data");



   try {


       // Write to the file
        FileOutputStream fileOutputStream = new FileOutputStream(textFile);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.append(data1);
        outputStreamWriter.append(data2);
        outputStreamWriter.close();
        fileOutputStream.close();

       Toast.makeText(getApplicationContext(), "Done writing to SD card", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
   }
AndroidKid
  • 21
  • 4

0 Answers0