【问题标题】:How to format and save console output to file in Java?如何格式化控制台输出并将其保存到Java中的文件?
【发布时间】: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


【解决方案1】:

在您的代码中,您永远不会使用您创建的 Format 类在输出前加上日期。您应该已经创建了这个类的一个实例,并调用了新创建实例的console 字段的println() 方法。下面是您的代码,稍作修改,我想它可以满足您的需求:

  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.PrintStream;
  import java.text.DateFormat;
  import java.text.SimpleDateFormat;
  import java.util.Date;

  public class So_47900381 {

    static 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 static void progStream() throws FileNotFoundException {
      File log = new File("log" + System.currentTimeMillis() + ".txt");
      PrintStream console = new PrintStream(new FileOutputStream(log));
      System.out.println("Writing to " + log.getPath());
      System.setOut(console);
      Format fmt = new Format();
      fmt.console.println("This is a test.");
    }

    public static void main(String[] args) {
      try {
       progStream();
      } catch (Exception x) { x.printStackTrace(); }
    }

  }

但我认为没有必要有一个单独的字段,它是PrintStream 的后代,用于在Format 类中打印。类本身也可以从PrintStream 继承。看下面的代码:

  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.PrintStream;
  import java.text.DateFormat;
  import java.text.SimpleDateFormat;
  import java.util.Date;

  public class So_47900381_1{

    static public class Format extends PrintStream {
      private static final DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

      public Format(File file) throws FileNotFoundException {
        super(file);
        System.setOut(this);
      }

      public void println(String x) {
        Date date = new Date();
        super.println("[" + sdf.format(date) + "] " + "program(" + x + ")");
      }
    }

    public static void progStream() throws FileNotFoundException {
      File log = new File("log" + System.currentTimeMillis() + ".txt");
      System.out.println("Writing to " + log.getPath());
      Format fmt = new Format(log);          // redirects the output to the file
      System.out.println("This is a test."); // now it's written to the file 
    }

    public static void main(String[] args) {
      try {
        progStream();
      } catch (Exception x) { x.printStackTrace(); }
    }

  }

是的,查看log4j 和/或谷歌搜索java logging

【讨论】:

  • 谢谢,这真的很有帮助。我有大约一两个星期的时间使用 Java,所以这对我来说是全新的。非常感谢您的回答。
  • @DavidMorales :) 然后将其标记为已接受 :) 请注意,我已经对其进行了一些更改 - System.out.println("This is a test.") 在后者 sn-p 中
【解决方案2】:

我认为这就是您想要实现的目标:

import java.lang.*;
import java.io.*;
import java.util.*;
import java.text.*;

public class HelloWorld {

  public static void main(String[] args) throws IOException {

    PrintStream console = new PrintStream(System.out);
    PrintStream file = new PrintStream(new FileOutputStream(new File("log" + System.currentTimeMillis() + ".txt")));  

    Format format = new Format();

    // console
    format.print("bla", console);

    // file
    format.print("bla", file);  
  }
}

public class Format {

  private static final DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

  public void print(String x, PrintStream stream) {
     Date date = new Date();
     stream.println("[" + sdf.format(date) + "] " + "program(" + x + ")");
  }

}

PS.:如果你真的想记录东西,我建议你考虑像 log4j 这样的记录框架。

PS。 2:System.setOut(stream) 似乎不是一个好主意,因为您的 standard output 将被重定向到该文件。

希望我的回答对你有帮助:)

【讨论】:

  • 谢谢!有效。最好的部分是我实际上明白我做错了什么。我将阅读有关日志框架的信息,感谢您的参考!
  • 很高兴我能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-15
  • 2011-10-29
相关资源
最近更新 更多