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

时间:2022-04-17 20:48:12

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?

我尝试过使用这个代码建议(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");
   }

11 个解决方案

#1


107  

You need to do something like this:

你需要这样做:

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

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

第二个语句是关键。它改变了所谓的“最终”体系的价值。out属性为提供的PrintStream值。

There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.

有类似的方法(setIn和setErr)来改变标准输入和错误流;参考. lang。系统javadocs细节。


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.

我只想补充一点,使用Log4j、Logback或标准Java Java .util之类的日志子系统通常是一个更好的主意。日志子系统。这些服务提供了通过运行时配置文件、对滚动日志文件的支持、对系统日志记录的支持等功能。

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

或者,如果你正在做的不是“日志记录”,那么考虑以下两种情况:

  • 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。

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.

玩弄(例如:重定向)系统。在您的JVM中,不希望发生这种情况的其他代码可能会导致令人不快的意外。

#2


25  

There is no need to write any code, just in cmd on the console you can write:

无需编写任何代码,只需在控制台的cmd中编写:

javac myFile.java
java ClassName > a.txt

The output data is stored in the a.txt file.

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

#3


19  

to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:

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

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

and used as in:

和使用:

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

(just an idea, not complete)

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

#4


10  

Create the following method:

创建以下方法:

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

(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)

(我没有在上面的类中包含适当的IO处理,它也不会编译——您自己做吧。还要考虑配置文件名。注意“真正”的论点。这意味着每次调用该方法时都不会重新创建该文件)

Then instead of System.out.println(str) call Logger.log(str)

然后不是System.out.println(str)调用Logger.log(str)

This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more

这种手工方法并不可取。使用日志记录框架- slf4j、log4j、common -logging等等

#5


7  

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

除了讨论的几种编程方法之外,另一个选项是从shell中重定向标准输出。这里有几个Unix和DOS示例。

#6


4  

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

您可以在程序开始时使用System. setout()来重定向所有的输出。输出到您自己的PrintStream。

#7


3  

This is my idea of what you are trying to do and it works fine:

这就是我对你所要做的事情的看法,它很有效:

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


1  

The easiest way to write console output to text file is

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

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

#9


1  

To write console output to a txt file

将控制台输出写入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();
    }
}

If you want to generate the PDF rather then the text file, you use the dependency given below:

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

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

To generate a PDF, use this code:

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

#10


0  

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

I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.

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

#11


0  

In netbeans, you can right click the mouse and then save as a .txt file. Then, based on the created .txt file, you can convert to the file in any format you want to get.

在netbeans中,可以右键单击鼠标,然后将其保存为.txt文件。然后,基于创建的.txt文件,您可以以任何您想要的格式转换到该文件。

#1


107  

You need to do something like this:

你需要这样做:

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

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

第二个语句是关键。它改变了所谓的“最终”体系的价值。out属性为提供的PrintStream值。

There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.

有类似的方法(setIn和setErr)来改变标准输入和错误流;参考. lang。系统javadocs细节。


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.

我只想补充一点,使用Log4j、Logback或标准Java Java .util之类的日志子系统通常是一个更好的主意。日志子系统。这些服务提供了通过运行时配置文件、对滚动日志文件的支持、对系统日志记录的支持等功能。

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

或者,如果你正在做的不是“日志记录”,那么考虑以下两种情况:

  • 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。

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.

玩弄(例如:重定向)系统。在您的JVM中,不希望发生这种情况的其他代码可能会导致令人不快的意外。

#2


25  

There is no need to write any code, just in cmd on the console you can write:

无需编写任何代码,只需在控制台的cmd中编写:

javac myFile.java
java ClassName > a.txt

The output data is stored in the a.txt file.

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

#3


19  

to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:

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

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

and used as in:

和使用:

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

(just an idea, not complete)

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

#4


10  

Create the following method:

创建以下方法:

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

(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)

(我没有在上面的类中包含适当的IO处理,它也不会编译——您自己做吧。还要考虑配置文件名。注意“真正”的论点。这意味着每次调用该方法时都不会重新创建该文件)

Then instead of System.out.println(str) call Logger.log(str)

然后不是System.out.println(str)调用Logger.log(str)

This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more

这种手工方法并不可取。使用日志记录框架- slf4j、log4j、common -logging等等

#5


7  

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

除了讨论的几种编程方法之外,另一个选项是从shell中重定向标准输出。这里有几个Unix和DOS示例。

#6


4  

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

您可以在程序开始时使用System. setout()来重定向所有的输出。输出到您自己的PrintStream。

#7


3  

This is my idea of what you are trying to do and it works fine:

这就是我对你所要做的事情的看法,它很有效:

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


1  

The easiest way to write console output to text file is

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

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

#9


1  

To write console output to a txt file

将控制台输出写入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();
    }
}

If you want to generate the PDF rather then the text file, you use the dependency given below:

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

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

To generate a PDF, use this code:

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

#10


0  

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

I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.

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

#11


0  

In netbeans, you can right click the mouse and then save as a .txt file. Then, based on the created .txt file, you can convert to the file in any format you want to get.

在netbeans中,可以右键单击鼠标,然后将其保存为.txt文件。然后,基于创建的.txt文件,您可以以任何您想要的格式转换到该文件。