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

69

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

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

1
你提供的代码示例将控制台输入写入文件。不太清楚你想要实现什么。能否提供更多细节? - daphshez
我在控制台上有很多输出,这些输出是由system.out.println产生的。我正在尝试将所有这些输出写入一个.txt文件中。 - Jessy
11个回答

132
您需要像这样做:

您需要像这样做:

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或标准Javajava.util.logging子系统这样的记录子系统。这些子系统通过运行时配置文件提供细粒度的日志记录控制,支持滚动日志文件,与系统日志共享等功能。

或者,如果您不是在进行“日志记录”,那么请考虑以下内容:

  • 对于典型的Shell,您可以将标准输出(或标准错误)重定向到命令行上的文件,例如:

$ java MyApp > output.txt   

需要更多信息,请参考shell教程或手册条目。

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

  • 更改System.out可能会对JVM中的其他代码造成意外的影响。(一个良好设计的Java库将避免依赖于System.outSystem.err,但你也可能会运气不佳。)


    37

    无需编写任何代码,只需在控制台中输入以下命令:

    javac myFile.java
    java ClassName > a.txt
    

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


    10
    如果您想要捕获错误输出,可以使用以下命令:"java ClassName > a.txt 2>&1"。例如,简单的"java -version"命令会写入console.err,您只能使用我的扩展程序来捕获它。请注意,该命令仅适用于标准输出。 - Heri
    2
    对于jar文件,使用以下命令:java -jar yourapp.jar > a.txt 2>&1 - user9268852

    27

    为了保留控制台输出,也就是将其写入文件并在控制台上显示,您可以使用类似以下的方法:

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

    (仅是一种想法,不完整)


    12
    创建以下方法:
    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);,它只会自动刷新。 - Ahmed Nassar
    每次创建新的printWriter时,文本文件都不会被改变吗? - Jürgen K.
    其中“true”参数之一是“append”,因此文本将被追加。 - Bozho
    PrintWriter 中,自动刷新设置为 true 似乎对于 write 不起作用,只有对于 printlnprintfformat 起作用。 - Halvor Holsten Strand
    抱歉,这不是英语,因此无法翻译。请提供正确的英文文本。 - Pixie

    7

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


    2
    抱歉,我在命令中漏掉了“&”符号。在Unix中的命令是:“java -jar yourApplication.jar >& yourLogFile.txt”。 - drzymala

    4

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


    3

    这是我对你试图做的事情的理解,它可以正常工作:

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

    1

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

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

    3
    请不要再进行像这样的编辑。您的编辑并没有明显的原因,只会让内容变得更糟。请不要滥用编辑以获取声望。 - Rob

    0

    将控制台输出写入文本文件

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

    1
    我认为读者不需要设置字符串列表的所有代码来编写;他们可以自己做到这一点。这个答案归结为“在将某些内容写入System.out之后,使用FileWriter或PdfWriter将其写入文件”。 - Noumenon
    @Noumenon 先生,您可能对Java有很多了解,但在这个公开论坛上有很多新手和初学者,完整的代码对他们来说是一个巨大的帮助。 - Ashish Vishnoi
    感谢您成熟的回应。您说得对,拥有可以实际运行和测试的东西确实有帮助——我也会提供可工作的示例。我只是不想在整个示例中寻找答案。如果在答案前加上摘要:“只需使用FileWriter将其写入文件。工作示例:”,这个答案就会更好。顺便说一下,Stack Overflow与开放式论坛不同,答案旨在帮助原始发布者以外的许多未来读者。他们更有可能尝试并投票支持易于一目了然的方法。 - Noumenon

    0
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileWriter("C:\\testing.txt"));
        } catch (IOException e) {
                e.printStackTrace();
        }
    out.println("output");
    out.close();
    

    我正在使用FileWriter的绝对路径。它对我非常有效。还要确保文件存在于该位置。否则,它会抛出FileNotFoundException异常。如果找不到文件,则此方法不会在目标位置创建新文件。


    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接