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

旧街凉风 提交于 2019-12-07 19:39:17

问题


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 (e.g. 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.


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/27546955/append-add-string-data-to-an-sd-card-text-file-in-an-android-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!