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

Java 如何将控制台输出写入txt文件,java,file-io,console,Java,File Io,Console,我曾尝试使用此代码建议()将控制台输出写入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 con

我曾尝试使用此代码建议()将控制台输出写入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");
   }

您可以在程序开始时使用,通过
System.out
将所有输出重定向到您自己的
PrintStream
创建以下方法:

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)
call
Logger.log(str)


这种手动方法并不可取。使用日志框架-slf4j、、以及更多功能,您需要执行以下操作:

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
第二句话是关键。它将假定的“final”
System.out
属性的值更改为提供的PrintStream值

有类似的方法(
setIn
setErr
)用于更改标准输入和错误流;有关详细信息,请参阅
java.lang.System
javadocs

以上内容的更一般版本如下:

PrintStream out = new PrintStream(
        new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
如果
append
true
,则流将追加到现有文件,而不是截断它。如果
autoflush
true
,则每当写入字节数组、调用
println
方法之一或写入
\n
时,都会刷新输出缓冲区


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

P>可选的,如果你不是“日志”,那么考虑以下内容:

  • 对于典型的shell,您可以将标准输出(或标准错误)重定向到命令行上的文件;e、 g

    $ java MyApp > output.txt   
    
    有关详细信息,请参阅shell教程或手动输入

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

更改
System.out
可能会让JVM中其他不希望发生这种情况的代码感到意外。(正确设计的Java库将避免依赖于
System.out
System.err
,但您可能不走运。)

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

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

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

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

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

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

无需编写任何代码,只需使用cmd即可 在控制台上,您可以编写:

javac myFile.java
java ClassName > a.txt
输出数据存储在a.txt文件中。

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

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

将控制台输出写入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();
    }
}
publicstaticvoidmain(字符串[]args){
int i;
List ls=新的ArrayList();
对于(i=1;i

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

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

您提供的代码示例将控制台输入写入一个文件。您试图实现的目标还不太清楚。您能提供更多详细信息吗?我在控制台上有许多由system.out.println生成的输出。我正在尝试编写所有这些输出o a.txt文件。抱歉,我在命令中漏掉了符号。unix中的命令是:“java-jar yourApplication.jar>&yourLogFile.txt”。这适用于标准输出。如果您还想捕获错误输出,请使用:“java ClassName>a.txt 2>&1”。例如,简单的“java-version”写入console.err,您只能使用我的扩展名捕获它。对于jar文件
java-jar yourapp.jar>a.txt 2>&1
您可能指的是
PrintWriter out=new PrintWriter(new FileWriter(“output.txt”,true),true);
,以便追加和自动刷新,而不是
PrintWriter out=new PrintWriter(new FileWriter(“output.txt”),true);
仅自动刷新。文本文件不是每次创建新的printWriter时都会更改吗?其中一个“true”参数是“append”“,因此文本将被添加到
PrintWriter
上自动刷新的
true
似乎不会为
write
刷新。只有
println
printf
格式
。БПааМ!Баааааааааааа请不要再像以前那样进行编辑。你主动让事情变得更糟-没有明确的原因。请不要滥用编辑来赢得声誉。我认为读者不需要所有的代码来设置字符串列表来编写;他们自己可以这样做。这个答案归结为“将某些内容写入System.out后,还可以使用FileWriter或PdfWriter将其写入文件"@Noumenon;先生,您可能对java有很多了解,但在这个开放论坛上,有很多新手和新手,完整的代码对他们有很大的帮助。感谢您成熟的响应。您是对的,它有助于您实际运行和测试一些东西——我也提供了工作示例。我只是不想o必须通读整个示例才能找到答案。如果前面加上
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();
    }
}
<dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.0.6</version>
</dependency>
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();
    }
}
PrintWriter out = null;
try {
    out = new PrintWriter(new FileWriter("C:\\testing.txt"));
    } catch (IOException e) {
            e.printStackTrace();
    }
out.println("output");
out.close();