使用OutputStreamWriter追加一个字符串到一个现有的文件字符串、文件、OutputStreamWriter

2023-09-04 06:58:51 作者:我是你的遗憾么

我不能够追加一个字符串使用 OutputStreamWriter 现有的文件。

据重写文件和旧数据已不存在:

 尝试{
    OutputStreamWriter outputStreamWriter =新OutputStreamWriter(openFileOutput(文件名,Context.MODE_PRIVATE));
    outputStreamWriter.append(消息);
    outputStreamWriter.close();
}
 

文件名是一个已经存在的文件。 的消息是一个字符串追加。

解决方案

使用MODE_APPEND而不是MODE_PRIVATE打开文件时。 您的问题已回答已经好几次,喜欢这里: Android的附加文本文件

更新

不同的模式标志的打开文件时的目的(来源:的JavaDoc ):

MODE_PRIVATE : 文件创建模式:默认模式,其中所创建的文件只能通过调用应用程序(或共享相同的用户ID的所有的应用程序)访问。 MODE_APPEND * :文件创建模式:与openFileOutput使用,如果文件已经存在,那么将数据写入到现有文件的末尾而不进行删除它。 MODE_ENABLE_WRITE_AHEAD_LOGGING :数据库开放的标志:当设置,数据库的打开与默认启用的预写日志 MODE_MULTIPROCESS :共享preference装载标志:当设置,磁盘上的文件都被检查,修改,即使共享preferences实例已加载在这个过程中。这种行为有时希望在情况下,应用程序有多个进程,都写相同的共享preferences文件。通常有更好的方式进程间的通信,虽然。这是传统的(但无证)行为和姜饼(Android 2.3的)前,目标定位等版本时,这个标志是隐含的。对于应用程序的目标定位SDK版本高于Android 2.3的,该标志必须显式设置如果需要的话。 的 MODE_WORLD_READABLE 的:德precated 的 MODE_WORLD_WRITEABLE 的:德precated 00022.12 转换流 OutputStreamWriter

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.

解决方案

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):

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). 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. MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag: when set, the database is opened with write-ahead logging enabled by default. 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. MODE_WORLD_READABLE: Deprecated MODE_WORLD_WRITEABLE: Deprecated