【问题标题】:How to write console output to a txt file如何将控制台输出写入 txt 文件
【发布时间】:2023-03-16 03:17:02
【问题描述】:

我尝试使用此代码建议 (http://www.daniweb.com/forums/thread23883.html#) 将控制台输出写入 txt 文件,但没有成功。怎么了?

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");
   }

【问题讨论】:

  • 您提供的代码示例将控制台 input 写入文件。目前还不是很清楚你想要达到什么目的。你能提供更多细节吗?
  • 我在控制台上有许多由 system.out.println 产生的输出。我正在尝试将所有这些输出写入 .txt 文件。

标签: java file-io console


【解决方案1】:

你需要做这样的事情:

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

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

有类似的方法(setInsetErr)来改变标准输入和错误流;有关详细信息,请参阅java.lang.System javadocs。

上面的一个更通用的版本是这样的:

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

如果appendtrue,则流将附加到现有文件而不是截断它。如果autoflushtrue,则每当写入字节数组、调用println 方法之一或写入\n 时,都会刷新输出缓冲区。


我想补充一点,使用 Log4jLogback 或标准 Java java.util.logging 子系统等日志记录子系统通常是一个更好的主意。它们通过运行时配置文件提供细粒度的日志控制、支持滚动日志文件、系统日志的提要等等。

或者,如果您不是“记录”,请考虑以下事项:

  • 使用典型的 shell,您可以将标准输出(或标准错误)重定向到命令行上的文件;例如

    $ java MyApp > output.txt   
    

    有关详细信息,请参阅 shell 教程或手动条目。

  • 您可以更改您的应用程序以使用作为方法参数或通过单例或依赖注入传递的out 流,而不是写入System.out

更改System.out 可能会给您的JVM 中的其他代码带来令人讨厌的意外,而这些代码并没有预料到会发生这种情况。 (一个设计合理的 Java 库会避免依赖 System.outSystem.err,但你可能会倒霉。)

【讨论】:

    【解决方案2】:

    无需编写任何代码,在cmd中即可 在控制台上你可以写:

    javac myFile.java
    java ClassName > a.txt
    

    输出数据存储在 a.txt 文件中。

    【讨论】:

    • 这适用于标准输出。如果您还想捕获错误输出,请使用:“java ClassName > a.txt 2>&1”。例如,简单的“java -version”写入console.err,您只能使用我的扩展程序捕获。
    • 对于jar文件java -jar yourapp.jar > a.txt 2>&1
    【解决方案3】:

    保留控制台输出,即写入文件并将其显示在控制台上,您可以使用如下类:

        public class TeePrintStream extends PrintStream {
            private final PrintStream second;
    
            public TeePrintStream(OutputStream main, PrintStream second) {
                super(main);
                this.second = second;
            }
    
            /**
             * Closes the main stream. 
             * The second stream is just flushed but <b>not</b> closed.
             * @see java.io.PrintStream#close()
             */
            @Override
            public void close() {
                // just for documentation
                super.close();
            }
    
            @Override
            public void flush() {
                super.flush();
                second.flush();
            }
    
            @Override
            public void write(byte[] buf, int off, int len) {
                super.write(buf, off, len);
                second.write(buf, off, len);
            }
    
            @Override
            public void write(int b) {
                super.write(b);
                second.write(b);
            }
    
            @Override
            public void write(byte[] b) throws IOException {
                super.write(b);
                second.write(b);
            }
        }
    

    并用于:

        FileOutputStream file = new FileOutputStream("test.txt");
        TeePrintStream tee = new TeePrintStream(file, System.out);
        System.setOut(tee);
    

    (只是一个想法,不完整)

    【讨论】:

      【解决方案4】:

      创建以下方法:

      public class Logger {
          public static void log(String message) { 
            PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
            out.write(message);
            out.close();
          }
      }
      

      (我没有在上面的类中包含正确的 IO 处理,它不会编译 - 自己做。还要考虑配置文件名。注意“true”参数。这意味着文件不会每次调用该方法时重新创建)

      然后代替System.out.println(str)调用Logger.log(str)

      这种手动方法不可取。使用日志框架 - slf4j、log4jcommons-logging 等等

      【讨论】:

      • 您可能指的是PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);,以便同时追加和自动刷新,而不是PrintWriter out = new PrintWriter(new FileWriter("output.txt"), true);,它只会自动刷新。
      • 不是每次新建printWriter都会改变文本文件吗?
      • “true”参数之一是“append”,所以文本会被追加
      • true 用于 PrintWriter 上的自动刷新似乎不适用于 write。只有printlnprintfformat
      • Ох, спаси ме! Благодаря ти :)
      【解决方案5】:

      除了讨论的几种编程方法之外,另一种选择是从 shell 重定向标准输出。这里有几个UnixDOS 的例子。

      【讨论】:

      • 对不起,我错过了命令中的 & 符号。 unix 中的命令是:“java -jar yourApplication.jar >& yourLogFile.txt”
      【解决方案6】:

      您可以在程序开始时使用System.setOut() 将所有通过System.out 的输出重定向到您自己的PrintStream

      【讨论】:

        【解决方案7】:

        这是我对您正在尝试做的事情的想法,并且效果很好:

        public static void main(String[] args) throws IOException{
        
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        
            BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
            try {
                String inputLine = null;
                do {
                    inputLine=in.readLine();
                    out.write(inputLine);
                    out.newLine();
                } while (!inputLine.equalsIgnoreCase("eof"));
                System.out.print("Write Successful");
            } catch(IOException e1) {
                System.out.println("Error during reading/writing");
            } finally {
                out.close();
                in.close();
            }
        }
        

        【讨论】:

          【解决方案8】:

          将控制台输出写入文本文件的最简单方法是

          //create a file first    
              PrintWriter outputfile = new PrintWriter(filename);
          //replace your System.out.print("your output");
              outputfile.print("your output");
              outputfile.close(); 
          

          【讨论】:

          • 请不要再像this那样进行编辑。你主动让事情变得更糟——没有明确的原因。请不要滥用编辑来获得声誉。
          【解决方案9】:

          将控制台输出写入 txt 文件

          public static void main(String[] args) {
              int i;
              List<String> ls = new ArrayList<String>();
              for (i = 1; i <= 100; i++) {
                  String str = null;
                  str = +i + ":-  HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
                  ls.add(str);
              }
              String listString = "";
              for (String s : ls) {
                  listString += s + "\n";
              }
              FileWriter writer = null;
              try {
                  writer = new FileWriter("final.txt");
                  writer.write(listString);
                  writer.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          

          如果您想生成 PDF 而不是文本文件,请使用下面给出的依赖项:

          <dependency>
                  <groupId>com.itextpdf</groupId>
                  <artifactId>itextpdf</artifactId>
                  <version>5.0.6</version>
          </dependency>
          

          要生成 PDF,请使用以下代码:

          public static void main(String[] args) {
              int i;
              List<String> ls = new ArrayList<String>();
              for (i = 1; i <= 100; i++) {
                  String str = null;
                  str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
                  ls.add(str);
              }
              String listString = "";
          
              for (String s : ls) {
                  listString += s + "\n";
              }
              Document document = new Document();
              try {
                  PdfWriter writer1 = PdfWriter
                          .getInstance(
                                  document,
                                  new FileOutputStream(
                                          "final_pdf.pdf"));
                  document.open();
                  document.add(new Paragraph(listString));
                  document.close();
                  writer1.close();
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              } catch (DocumentException e) {
                  e.printStackTrace();
              }
          }
          

          【讨论】:

          • 我认为读者不需要所有的代码来设置一个字符串列表来编写;他们可以自己做。这个答案归结为“在向 System.out 写入内容后,还要将其写入带有 FileWriter 或 PdfWriter 的文件”。
          • @Noumenon;先生,您可能对 java 有很多了解,但是在这个开放的论坛上,有很多新人,完整的代码对他们有很大的帮助。
          • 感谢成熟的回复。没错,拥有可以实际运行和测试的东西会有所帮助——我也提供了工作示例。我只是不想通读整个示例来找到答案。如果前面有一个摘要,同样的答案会得到改进:“只需使用 FileWriter 将其写入文件。工作示例:”作为旁注,Stack Overflow 与开放论坛不同,因为答案旨在帮助许多未来的读者除了原始海报。他们更有可能尝试并赞成一种一目了然的方法。
          【解决方案10】:
          PrintWriter out = null;
          try {
              out = new PrintWriter(new FileWriter("C:\\testing.txt"));
              } catch (IOException e) {
                      e.printStackTrace();
              }
          out.println("output");
          out.close();
          

          我正在使用 FileWriter 的绝对路径。它对我来说就像一种魅力。还要确保该文件存在于该位置。否则它将抛出 FileNotFoundException。如果找不到文件,此方法不会在目标位置创建新文件。

          【讨论】:

            【解决方案11】:

            在 netbeans 中,您可以右键单击鼠标,然后将其另存为 .txt 文件。然后,根据创建的 .txt 文件,您可以转换为您想要获取的任何格式的文件。

            【讨论】:

            • 你误解了这个问题。
            猜你喜欢
            • 1970-01-01
            • 2012-12-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-30
            • 1970-01-01
            相关资源
            最近更新 更多