Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutputStreamWriter does not append

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

like image 861
LadyWinter Avatar asked Oct 13 '14 09:10

LadyWinter


People also ask

How do you tell FileOutputStream to append data to a file?

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 .

What is the default encoding for an output stream writer?

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.

What is OutputStream Writer?

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.


1 Answers

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.

like image 56
Okas Avatar answered Sep 20 '22 19:09

Okas