Java 如果文件存在,则 PrintWriter 附加数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24982744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:11:35  来源:igfitidea点击:

PrintWriter to append data if file exist

javafileoutputstreamprintwriter

提问by TheWaveLad

I have a savegame file called mysave.savand I want to add data to this file if the file already exists. If the file doesn't exists, I want to create the file and then add the data.

我有一个游戏存档文件mysave.sav,如果该文件已经存在,我想将数据添加到该文件中。如果文件不存在,我想创建文件然后添加数据。

Adding data works fine. But appending data overwrites existing data. I followed the instructions of axtavt here (PrintWriter append method not appending).

添加数据工作正常。但是附加数据会覆盖现有数据。我按照 axtavt 的说明进行操作(PrintWriter append method not append)。

    String savestr = "mysave.sav"; 
    File f = new File(savestr);
    PrintWriter out = new PrintWriter(savestr);

    if ( f.exists() && !f.isDirectory() ) {
        out = new PrintWriter(new FileOutputStream(new File(savestr), true));
        out.append(mapstring);
        out.close();
    }
    else {
        out.println(mapstring);
        out.close();
    }

where mapstringis the string I want to append. Can you help me? Thank you!

mapstring我要附加的字符串在哪里。你能帮助我吗?谢谢!

采纳答案by Braj

Once you call PrintWriter out = new PrintWriter(savestr);the file is created if doesn't exist hence first check for file existence then initialize it.

一旦您调用PrintWriter out = new PrintWriter(savestr);该文件,如果不存在则创建该文件,因此首先检查文件是否存在,然后对其进行初始化。

As mentioned in it's Constructor Docmentationas well that says:

正如它的构造函数文档中提到的那样:

If the file exists then it will be truncated to zero size; otherwise, a new file will be created.

如果文件存在,那么它将被截断为零大小;否则,将创建一个新文件。

Since file is created before calling f.exists()hence it will return truealways and ìfblock is never executed at all.

由于文件是在调用之前创建的,f.exists()因此它将true始终返回并且ìf根本不会执行块。

Sample code:

示例代码:

String savestr = "mysave.sav"; 
File f = new File(savestr);

PrintWriter out = null;
if ( f.exists() && !f.isDirectory() ) {
    out = new PrintWriter(new FileOutputStream(new File(savestr), true));
}
else {
    out = new PrintWriter(savestr);
}
out.append(mapstring);
out.close();

For better resource handling use Java 7 - The try-with-resources Statement

为了更好的资源处理使用 Java 7 - The try-with-resources Statement