gpt4 book ai didi

java - 将字符串输出到文件中,而不清除文件

转载 作者:行者123 更新时间:2023-11-29 10:18:23 25 4
gpt4 key购买 nike

我一直在使用 BufferedWriter 对文本文件进行“记录”,但遇到了一个问题:

我运行以下代码..相当基础..

BufferedWriter out = new BufferedWriter(new FileWriter(path+fileName));
String str = "blabla";
out.write(str);
out.close();

接下来我知道的是,包含几行文本的整个文件已被清除,只有“blabla”存在。

我应该使用什么类来让它添加一个新行,文本为“blabla”,而不必将整个文件文本转换为字符串并将其添加到“blabla”之前的“str”?

最佳答案

What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?

您正在使用正确的类(好吧,也许 - 见下文) - 您只是没有检查构造选项。你想要 FileWriter(String, boolean)构造函数重载,其中第二个参数确定是否追加到现有文件。

但是:

  • 一般来说,我建议不要使用 FileWriter,因为您无法指定编码。尽管很烦人,但最好使用 FileOutputStream 并将其包装在具有正确编码的 OutputStreamWriter 中。
  • 与其使用 path + fileName 组合目录和文件名,不如使用 File:

    new File(path, fileName);

    这让核心库可以处理不同的目录分隔符等。

  • 确保使用 finally block 关闭输出(这样即使抛出异常也能进行清理),或者如果您使用的是 Java,则使用“try-with-resources” block 7.

所以把它们放在一起,我会使用:

String encoding = "UTF-8"; // Or use a Charset
File file = new File(path, fileName);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), encoding));
try {
out.write(...);
} finally {
out.close()'
}

关于java - 将字符串输出到文件中,而不清除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11809565/

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