如何将控制台输出写入txt文件

如何将控制台输出写入txt文件

本文介绍了如何将控制台输出写入txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此代码建议将控制台输出写入txt文件(),但我不成功。发生了什么问题?

I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What's wrong?

try {
      //create a buffered reader that connects to the console, we use it so we can read lines
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

      //read a line from the console
      String lineFromInput = in.readLine();

      //create an print writer for writing to a file
      PrintWriter out = new PrintWriter(new FileWriter("output.txt"));

      //output to the file a line
      out.println(lineFromInput);

      //close the file (VERY IMPORTANT!)
      out.close();
   }
      catch(IOException e1) {
        System.out.println("Error during reading/writing");
   }


推荐答案

this:

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);

第二个语句是关键。它将所谓的最终 System.out 属性的值更改为提供的PrintStream值。

The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.

我想补充一点,使用,或标准Java subsystem。这些提供了诸如通过运行时配置文件的细粒度日志记录控制,对滚动日志文件的支持,对系统日志记录的馈送等。

I'd just like to add that it is generally a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer such things as fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging.

或者,如果你所做的不是logging,然后考虑:

Or, if what you are doing is not "logging", then consider either:


  • 将标准输出重定向到命令行上的文件,或

  • 更改您的应用程序以使用作为参数传递的 out 流,而不是写入 System.out 。 / li>
  • redirecting standard output to a file on the command line, or
  • changing your application to use an out stream passed as a parameter rather than writing to System.out.

使用(例如重定向) System.out 对您的JVM中的其他代码的惊喜,不希望发生这种情况。

Messing around with (e.g. redirecting) System.out is liable to cause nasty surprises for other code in your JVM that is not expecting this to happen.

这篇关于如何将控制台输出写入txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:03