gpt4 book ai didi

Java通过多种方法打印到文件并附加文本

转载 作者:行者123 更新时间:2023-11-30 06:04:02 25 4
gpt4 key购买 nike

我想用几种方法编写一个小程序,并且希望能够将不同方法的不同内容打印到输出文件中。如何从 main 之外的每个方法打印到最后一行后附加的同一文件中。我也对 PrintWriter 之外的其他方法持开放态度。

package tennisoddssimulator;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class TennisOddsSimulator {

private static final int TOTALMATCHES = 1000;
private boolean bestOf5Sets;
private boolean P2ToServe;

public static void main(String[] args)
throws
FileNotFoundException,
UnsupportedEncodingException {

PrintWriter writer
= new PrintWriter("output.txt", "UTF-8");

for (int i = 0; i < TOTALMATCHES; i++) {

}
writer.close();
}

public static void printMatchNo(int matchNo) {
/*I want to print the number
of the match currently being
simulated from this method by
calling this method after the
start of every match*/
}

public static void printGameScore() {
/*I want to print the current
game score from this method by
calling this method after every
point has scored in a match*/
}

public static void furtherMethodForPrinting1() {
/*You've probably got the
idea by now*/
}

public static void furtherMethodForPrinting2() {
}
}

最佳答案

我实际上建议在每个辅助方法中打开一个新的 PrintWriter,例如

public static void printMatchNo(int matchNo) {
try {
OutputStream os = new FileOutputStream("output.txt", true); // append mode
Writer writer = new OutputStreamWriter(outputStream, "UTF8");
PrintWriter pwFile = new PrintWriter(writer);
pwFile.write("The match number is: " + matchNo);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (pwFile != null) {
pwFile.close();
}
}
}

我推荐这种方法的原因是,在程序中保持 PrintWriter 永久打开可能没有意义。相反,您应该只打开一个,写入,然后在需要时关闭。

顺便说一句,如果您这样做只是为了提供信息,您可能需要考虑使用可用于 Java 的日志框架之一。配置完成后,您只需调用一个简单的方法即可写入日志文件。

关于Java通过多种方法打印到文件并附加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51728055/

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