编写一个Java文件,需要在每次运行时将其清除 [英] Writing a java file, need it to be cleared each run

查看:154
本文介绍了编写一个Java文件,需要在每次运行时将其清除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java FileWriter从一个文件中获取一些数据,这些数据会进行一些转换并放入输出文件中.我希望输出文件至少要清除,如果每次运行我的应用程序后都不要删除,那么我的问题就是我将如何实现?

I'm using Java FileWriter to take some data from one file, that will do undergo some transformation and be put in to an output file. I want the output file to be at least cleared, if not deleted after each time I run my app so my question is just how would I achieve this?

这是我到目前为止所得到的:

This is what I've got so far:

try {
    file = new File(filepath);
    fileWriter = new FileWriter(file, true);
    fileWriter.write(data.toJSONString() + "\n");
    fileWriter.flush();
    fileWriter.close();
} 
catch (IOException e) {
e.printStackTrace();
}
System.out.print(data + "\n");
System.out.print(o + "\n");
}
file.createNewFile();

推荐答案

如果您不想追加到文件,则对第二个参数使用正确的FileWriter构造函数参数值,"追加"参数:

If you don't want to append to the file then use the correct FileWriter constructor parameter values for the second parameter, the "append" parameter:

不是:

fileWriter = new FileWriter(file, true);

但是:

fileWriter = new FileWriter(file, false);

与往常一样,请检查FileWriter API以获取详细信息.

As usual, please check the FileWriter API for the details.

修改
您声明:

Edit
You state:

在这一点上,我可能只是让自己感到困惑-当我将append设置为false时,它将替换循环的最后一次运行中文件中的内容,因此我只结束了最后一行-好吧,我想要在程序运行时逐行输入数据,完成后我希望将文件保留在那里,直到下一次运行-那时我想清除内容.

I am probably just confusing myself too much at this point - when I set append to false, it replaces what was in the file in the last run of my loop, so I end up with just the last line - well I want to feed the data in line by line while the program runs, when it finishes I want the file to be left there, until the next run - at that point I want to clear the contents..

听起来好像您在循环的每次迭代中都创建了一个新的FileWriter.如果是这样,那就不要.创建一个FileWriter,将第二个构造函数参数设置为false,然后在循环中 创建它.然后循环使用它,而无需在循环中重新创建它,然后当循环结束并且您可以完全使用它时,将其关闭.简化事情.

It sounds like you're creating a new FileWriter with each iteration of the loop. If so, don't. Create one FileWriter with the second constructor parameter set to false, and create it before your loop. Then loop with it, without re-creating it in the loop, and then when the loop is over and you're through using it, close it. Simplify things.

这篇关于编写一个Java文件,需要在每次运行时将其清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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