简体   繁体   中英

Append (add) String data to an SD Card text file in an Android application

Just a quick point here. Although my code seems to be okay storing String data etc. in a new file using the standard techniques of writing to a mytext.txt file in an internal or external (SD Card) storage, it is of more use to me for my App to add more data to the same file in the same directory by repeating allowing the user to repeat the process (eg a user input and button save) or closing the App and starting over again, so the data permanently remains unless the user chooses to manually delete that data. Using conditional statements to check if the file or directory exists appears to make no difference to the situation and I get the same result as before (one answer). Also changing a writing method such as osw.write(myStr); to osw.append(myStr); remains the same. There are no errors in the code or application. Here is typical code in part of the MainActivity Java file

//earlier code
try
{
    File sdCard = Environment.getExternalStorageDirectory();
    File directory = new File (sdCard.getAbsolutePath() +
    "/MyFiles");
    if (!directory.exists())
    {
        directory.mkdirs();
    }

    File file = new File(directory, "mytext.txt");
     if (!file.exists()) 
     {    
         file.createNewFile();
     } 
    FileOutputStream fOut = new FileOutputStream(file);

    OutputStreamWriter osw = new
            OutputStreamWriter(fOut);

//---write the string to the file---
osw.write(myStr);
osw.flush();
osw.close();

}
catch (IOException ioe)
{
ioe.printStackTrace();
}

// continued code ...

ps. On my device, the mytext.txt file is stored in Internal storage (possible name sdcard0 ?) rather than expecting it to be in the the accessible/removable SD Card.

Change

FileOutputStream fOut = new FileOutputStream(file);

to

FileOutputStream fOut = new FileOutputStream(file, true);

see http://developer.android.com/reference/java/io/FileOutputStream.html#FileOutputStream(java.io.File , boolean)

to do this , u need to read the pre-existing text file and convert it into string.

then append the string.

delete the textfile

write the file at same location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM