【发布时间】:2017-12-20 06:57:26
【问题描述】:
背景:您好!首先,请记住我对Java相当陌生,因此,如果我有什么问题,请原谅我。我一直在尝试格式化我的控制台并将其输出保存到文本文件 2 天。到目前为止,这是我的代码:
我正在尝试将控制台的格式设置为
[12/20/2017 23:55:30] 节目(此处留言)
而我是这样做的:
public class Format {
private static final DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
PrintStream console = new PrintStream(System.out) {
public void println(String x) {
Date date = new Date();
super.println("[" + sdf.format(date) + "] " + "program(" + x + ")");
}
};
除此之外:
public void progStream() throws FileNotFoundException {
System.setOut(console);
System.out.println("This is a test.");
}
到这里它工作得很好,我可以看到所有系统输出都以正确的格式显示在 Eclipse 的控制台上。但是,当我尝试将其保存为文本文件时,它仅保存消息。没有格式。
public void progStream() throws FileNotFoundException {
File log = new File("log" + System.currentTimeMillis() + ".txt");
FileOutputStream fos = new FileOutputStream(log);
PrintStream console = new PrintStream(fos);
System.setOut(console);
System.out.println("This is a test.");
}
我尝试用console.print("message"); 替换System.out.println("message");,但我遇到了同样的问题。不幸的是,我已经用完了教程和论坛,但我仍然找不到解决方案。感谢您的帮助。
【问题讨论】:
-
使用日志 API,核心 API 内置了一个,或者您可以使用
Log4j -
你可以尝试发布一个简单的完整代码,因为部分代码很难理解
标签: java file console format output