gpt4 book ai didi

java - PrintWriter 覆盖每个单词或不覆盖整个文件

转载 作者:行者123 更新时间:2023-12-01 11:40:08 25 4
gpt4 key购买 nike

我有一个关于 PrintWriter 类的问题。我正在尝试在文件中写入长文本。起初,我遇到了覆盖问题。每次我运行它时,只会看到最后一个词。然后,我添加了 FileWriter,但是这次每当我再次运行它时它都不会覆盖该文件。

private static void storyTeller(String wordsToWrite) throws IOException {
Scanner scan = new Scanner(wordsToWrite);
PrintWriter out = new PrintWriter(new FileWriter(outFile, true));
String temp;

while (scan.hasNext()) {
temp = scan.next();
if (counter == 0) {
out.print(temp);
System.out.print(temp);
}
counter = counter + temp.length() + 1;
if (counter > 80) {
System.out.println();
out.println();
System.out.print(temp);
out.print(temp);
counter = temp.length() + 1;
}
else{
System.out.print(" " + temp);
out.print(" " + temp);
}

}
scan.close();
out.close();
}

如果我不向PrintWriter添加FileWriter参数,则outFile中只有一个单词(最后一个单词)。如果我像上面的代码一样添加“new FileWriter(outFile, true)”,这次当我再次运行程序时它不会覆盖。

这是我用 FileWriter 得到的,但每次运行程序时我都需要覆盖

This one is what I get with FileWriter, but I need to overwrite each time I run the program

这是我删除 FileWriter 进行覆盖时得到的结果

This is what I get when I delete FileWriter for overwriting

谢谢。

最佳答案

我终于知道如何解决这个问题了。每次启动程序时我都会删除该文件。而且,我使用了这条线,如上所示。

PrintWriter out = new PrintWriter(new FileWriter(outFile, true));'

如果我不删除该文件,程序不会覆盖该文件。相反,它会继续在已写入文件的末尾写入新文本。

关于java - PrintWriter 覆盖每个单词或不覆盖整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29597789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com