我如何使用FileWriter在文件内附加文本

时间:2019-06-17 13:53:35

标签: java android filewriter

我正在尝试继续向文件中添加文本(内部存储) 它使用FileOutputStream尝试过,很好,但是在我更改为使用FileWriter之后,我开始出现只读文件系统错误

        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

1 个答案:

答案 0 :(得分:0)

    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