Search code examples
javaandroidfilewriter

how do i append text inside a file using FileWriter


I'm trying to keep adding text into my file (internal storage) it was tried using FileOutputStream and it was fine but after i changed to use FileWriter then i started having the read-only file-system error

        EditText edd = findViewById(R.id.editTextData);
        Spinner spp = findViewById(R.id.spinnerCategory);

        String text1 = edd.getText().toString();
        String text2 = spp.getSelectedItem().toString();

        String filepath = text2 + ".txt";

        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(filepath, true));
            bw.write(text1);
            bw.newLine();
            bw.close();
            Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        } //End try catch statement

    }```

It's supposed to say Information Saved but i keep getting read-only file system

Solution

  •     EditText edd = findViewById(R.id.editTextData);
        Spinner spp = findViewById(R.id.spinnerCategory);
    
        String text1 = edd.getText().toString();
        String text2 = spp.getSelectedItem().toString();
    
        String filename = text2 + ".dat";
    
        try {
            File fa = new File(getFilesDir(),filename); //getting the filename path
            FileWriter fw = new FileWriter(fa,true);
            fw.write(text1 + "\n");
            fw.close();
            Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
        } catch (Exception e)
        {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        } //End try catch statement