OutputStreamWriter does not append

自作多情 提交于 2019-12-01 00:45:37

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26336623/outputstreamwriter-does-not-append

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