-1

I'm not able to append a string to existing file using OutputStreamWriter.

It rewrites the file and old data no longer exists:

try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("filename", Context.MODE_PRIVATE));
    outputStreamWriter.append(message);
    outputStreamWriter.close();
}

"filename" is a file that already exists. message is a string to append.

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
sourabh
  • 43
  • 2
  • 5

1 Answers1

3

Use MODE_APPEND instead of MODE_PRIVATE when opening the file. Your question has been answered already several times, like here: Android append text file

Update

The purpose of different mode flags when opening a file (source: JavaDocs):

  1. MODE_PRIVATE: File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
  2. MODE_APPEND*: File creation mode: for use with openFileOutput, if the file already exists then write data to the end of the existing file instead of erasing it.
  3. MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag: when set, the database is opened with write-ahead logging enabled by default.
  4. MODE_MULTIPROCESS: SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though. This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targetting such releases. For applications targetting SDK versions greater than Android 2.3, this flag must be explicitly set if desired.
  5. MODE_WORLD_READABLE: Deprecated
  6. MODE_WORLD_WRITEABLE: Deprecated
Community
  • 1
  • 1
rekaszeru
  • 19,130
  • 7
  • 59
  • 73