自动在"System.out.println()"语句中显示日期

Erc*_*sen 4 java minecraft

我知道您打印的每一行都可以用日期标记(并且还保存为日志文件).

例如在Minecraft中:

[16:21:43 INFO]: Minecraft Launcher 1.3.9 (through bootstrap 5) started on windows...
Run Code Online (Sandbox Code Playgroud)

我怎么做?也许和Logger一起?或者是否需要外部图书馆?

Pop*_*ibo 6

可以通过调用在String中显示前缀的日期 System.out.println

  1. 创建自定义PrintStream
  2. 覆盖println方法为String添加日期前缀
  3. System.setOut使用您的自定义设置PrintStream

自定义流:

public class MyPrintStream extends PrintStream {

    public MyPrintStream(OutputStream out) {
        super(out);
    }

    @Override
    public void println(String string) {
        Date date = new Date();
        super.println("[" + date.toString() + "] " + string);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试类:

 public static void main(String[] args) {
            System.setOut(new MyPrintStream(System.out));
            System.out.println("Hello World!");
                System.out.println("Yellow World!");
        }
Run Code Online (Sandbox Code Playgroud)

输出:

[Mon Feb 10 21:10:14 IST 2014] Hello World!
[Mon Feb 10 21:10:14 IST 2014] Yellow World!
Run Code Online (Sandbox Code Playgroud)