[英]How to write more than one object result to one output text file in Java?
我有多个具有不同输出的对象,我想在一个文本文件中打印所有结果,每个对象的结果在一行上而不覆盖任何值。
我写了以下代码; 但是,输出文本文件仅保存最后一个对象(Object2)的值。 我希望输出文件保存结果如下:
Q = 1
Q = 2
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Output {
public static int Q;
public static void main(String[] args) {
Object1();
Object2();
}
public static void Object1() {
Q = 1;
Print();
}
public static void Object2() {
Q = 2;
Print();
}
public static void Print() {
PrintWriter writer;
try {
writer = new PrintWriter("C:\\Users\\My Document\\Desktop\\Out.txt");
if (Q == 1) {
writer.println("Q =" + 1);
}
if (Q == 2) {
writer.println("Q = " + 2);
}
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
FileWriter
是解决这个问题的正确方法。 您也不需要将它包装在任何东西中。
在构造函数中指定true
将启用追加模式(因此在后续运行时要小心)。 由于Q不能同时为1和2,所以在完成块后我们写了一个新行。
由于这是一个try-with-resources语句,因此您无需担心在完成后关闭资源,因为这会照顾您。
try (FileWriter writer = new FileWriter("test.txt", true)) {
if (Q == 1) {
writer.write("Q =" + 1);
}
if (Q == 2) {
writer.write("Q = " + 2);
}
writer.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
您正在使用新信息覆盖Out.txt
文件。 您需要附加数据。
用这个替换你的行:
writer = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\My Document\\Desktop\\Out.txt", true)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.