如果文件存在,PrintWriter将附加数据 [英] PrintWriter to append data if file exist

查看:599
本文介绍了如果文件存在,PrintWriter将附加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 mysave.sav 的savegame文件,如果该文件已存在,我想将数据添加到此文件中。如果该文件不存在,我想创建该文件,然后添加数据。

I have a savegame file called mysave.sav and 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.

添加数据工作正常。但附加数据会覆盖现有数据。我按照axtavt的说明进行操作( PrintWriter追加方法不附加)。

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

    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();
    }

其中 mapstring 是我要追加的字符串。你能帮助我吗?谢谢!

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

推荐答案

一旦你打电话给 PrintWriter out = new PrintWriter(savestr); 如果文件不存在则创建文件因此首先检查文件是否存在然后初始化它。

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.

如上所述构造函数Docmentation 也说:


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

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

因为文件是在调用之前创建的.f.exists()因此它将返回 true 始终和f 块永远不会执行。

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

示例代码:

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();

为了更好地处理资源,请使用 Java 7 - try-with-resources Statement

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

这篇关于如果文件存在,PrintWriter将附加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆