Original code and its working saving the data to the SD Card
// Writing data to internal storage
btnSaveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isSDCardWritable()) {
String dataToSave = etData.getText().toString();
try {
// SD Card Storage
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/MyFiles");
directory.mkdirs();
File file = new File(directory, "text.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
// write the string to the file
osw.write(dataToSave);
osw.flush();
osw.close();
. . .
And then I changed the code to append a new values as it should be according to what I need:
osw.append(dataToSave);
osw.flush();
osw.close();
Problem is: It overwrites the text file instead of appending. What did I miss? Thanks for helping
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .
The default encoding is taken from the "file. encoding" system property. OutputStreamWriter contains a buffer of bytes to be written to target stream and converts these into characters as needed. The buffer size is 8K.
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset . The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
Constructor FileOutputStream( File file ) always overwrites file. If you want to append to file you have to use more generic constructor FileOutputStream( File file, boolean append ). If you set parameter 'append' to true file is not overwritten.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With