OutputStreamWriter does not add

The source code and its work with saving data on 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 add new values, as this should be in accordance with what I need:

  osw.append(dataToSave); osw.flush(); osw.close(); 

Problem: it overwrites the text file instead of adding. What am I missing? Thanks for helping

+7
android text-files android-sdcard fileoutputstream
source share
1 answer

The FileOutputStream constructor (File) always overwrites the file. If you want to add to a file, you need to use the more general FileOutputStream constructor (file file, boolean append). If you set the 'append' parameter to true, the file will not be overwritten.

+16
source share

All Articles