如何在Java中向.txt文件中添加新信息而不删除任何旧数据。

huangapple go评论67阅读模式
英文:

How can I add new information to a .txt file without it removing any old data in java

问题

我想将所有销售记录存储在一个txt文件中,但每次输入新信息时都会删除旧信息。有任何想法为什么会这样吗?

try {
    BufferedWriter bfw = new BufferedWriter(new FileWriter(file1));
    BufferedWriter bfw1 = new BufferedWriter(new FileWriter(file2));

    bfw.write(Total.getText());
    bfw.newLine();

    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    bfw1.write(timeStamp);
    bfw1.newLine();

    bfw.close();
    bfw1.close();
} catch (IOException ex) {
    Logger.getLogger(FrmFacturas.class.getName()).log(Level.SEVERE, null, ex);
}
英文:

I want to store all the sales in a txt file, but every time I enter new information it deletes the old information. Any idea why?

try {
    BufferedWriter bfw = new BufferedWriter(new FileWriter(file1));
    BufferedWriter bfw1 = new BufferedWriter(new FileWriter(file2));

    bfw.write(Total.getText());
    bfw.newLine();

    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    bfw1.write(timeStamp);
    bfw1.newLine();

    bfw.close();
    bfw1.close();
} catch (IOException ex) {
    Logger.getLogger(FrmFacturas.class.getName()).log(Level.SEVERE, null, ex);
}

答案1

得分: 1

你可以在FileWriter构造函数中加入第二个参数:

BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));

或者

你可以使用Files.nio:

Files.writeString(file1.toPath(), textToWrite, StandardOpenOption.APPEND)

英文:

You can put a second parameter to the FileWriter constructor:

BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));

OR

you could use Files.nio:

Files.writeString(file1.toPath(), textToWrite, StandardOpenOption.APPEND)

答案2

得分: 0

你必须以追加模式打开文件,要做到这一点,在FileWriter中的第二个参数中添加true。

BufferedWriter bfw = new BufferedWriter(new FileWriter(file1, true));
英文:

You have to open the file in append mode to do this add true as the second parameter in FileWriter

BufferedWriter bfw = new BufferedWriter(new FileWriter(file1,true));

huangapple
  • 本文由 发表于 2020年10月22日 05:27:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64471961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定