Problem adding file in android

I am creating an Android application that reads and writes data to a file in a location /sdcard/ReadandWrite/. When I write to this file, it does not write to append mode.it deletes the old data and writes the new one. please help me solve this. Here is my code.

private File openfile() {
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
    dir.mkdirs();
    File file = new File(dir, "myfile.txt");
    file.setWritable(true);
    if(file.exists())
    {
        file.canRead();
        file.setWritable(true);

    }
    else {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}

private void writetofile() {


    try {
        File file=openfile();
        OutputStreamWriter myOutWriter =
                new OutputStreamWriter(new FileOutputStream(file));
        myOutWriter.append(text.getText());

        myOutWriter.close();
        myOutWriter.close();
        Toast.makeText(getBaseContext(),
                "Done writing SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }
+4
source share
1 answer

You need to configure FileOutputStream to use mode append. From the JDK Documentation :

public FileOutputStream (string name, boolean append) throws a FileNotFoundException

. , , . FileDescriptor .

-, , checkWrite .

, , , , - FileNotFoundException.

:     name -     append - true, , . Throws:     FileNotFoundException - , , , , - .     SecurityException - checkWrite . :     JDK1.1 . :     SecurityManager.checkWrite(java.lang.String)

, OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));

OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));

+3

All Articles