gpt4 book ai didi

java - 如何在多个类中使用相同的 printwriter (java)

转载 作者:行者123 更新时间:2023-11-30 10:26:42 24 4
gpt4 key购买 nike

我正在开发一个小程序,它要求我从文件中读取一组参数,在 3 个类中对它们执行一些 if else 操作(所有 3 个类都继承相同的父类)。在每次操作之后,该方法应该像这样在输出文件中打印一行

方法1的输出1方法 2 的输出 1方法 1 的输出 2方法1的输出3等

想法是所有 3 个类的所有方法都应该打印在同一个文件中,顺序并不重要。

我在每个方法/if block 的末尾都使用了这段代码

if/method {
.... do something
text ="output of something";
try(PrintWriter out = new PrintWriter("outputfile.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}//end if/method

代码确实向文件中写入了一些内容,但它总是会覆盖前一行。因此,例如,我只有 1 行而不是 12 行“某物”。

我该如何解决这个问题?我怀疑这是因为我每次都创建一个新的 PrintWriter 并考虑过在其他地方声明它并将它调用到每个类。那行得通吗?我将如何在每个类(class)调用它?

这是我第一次使用文件。谢谢。

最佳答案

您用来创建 PrintWriter 的构造函数在内部使用了 FileOutputStream 的新实例。

FileOutputStream 有两种通用的写入模型:

  • 覆盖(默认)
  • 附加

由于您没有指定要使用的模式,您的编写器将使用默认模式。要告诉它您想要哪种模式,您需要使用正确的模式创建 FileOutputStream。例如,像这样:

try(PrintWriter out = new PrintWriter(new FileOutputStream("outputfile.txt", true))) {
// note the boolean parameter in FileOS constructor above. Its "true" value means "Append"
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

关于每个类创建自己的 PrintWriter 也有一些话要说:

  • 它重复了逻辑
  • 它(可能是不必要的)将你的类所做的任何操作与输出操作特别绑定(bind)到一个文件中(如果你想改写 HTTP 怎么办?)
  • 打开一个文件的操作通常并不便宜,所以你在那里失去了性能

我建议不是每个类都创建自己的输出设施,而是应该从外部接收一个:

class MyClass {
public void outputTo(PrintWriter w) {
String text = ...
w.println(text);
}
}

and you use it like this:

try (FileOutputStream fos = new FileOutputStream("filename", append);
PrintWriter w = new PrintWriter(fos)) {
new MyClass().outputTo(w); // first instance
new MyClass().outputTo(w); // second instance
//... etc.
}

关于java - 如何在多个类中使用相同的 printwriter (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589797/

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