java - 将所有java输出写入txt文件中

标签 java printing output bufferedreader printwriter

我想知道如何将 java 输出中的所有行写入 .txt 文件中。
到目前为止我已经做了一些测试,但我似乎无法找到解决方案:/
这是一个小代码,如果您能向我展示这个代码,我将不胜感激:
下面显示的代码询问用户在 .txt 文件中写入什么内容,但我希望它将所有打印行写入 .txt 文件中,而不询问用户任何内容。谢谢

package test;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;


public class Test {

    public static void main(String[] args)throws Exception {
        System.out.println("Hello");
        System.out.println("Hi");
        System.out.println("Hola");
        System.out.println("Bonjour");
        System.out.println("Hallo");
        System.out.println("Hej");
        System.out.println("Alo");
        System.out.println("Ciao");
        writeOutput();

    }
    public static void writeOutput() throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String lineFromInput = in.readLine();
        PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
        System.setOut(out);
        out.println(lineFromInput);
        out.close();
    }

}

最佳答案

直接使用PrintStream写入String值。

public static void main(String[] args)throws Exception {          
    PrintStream printStream = new PrintStream(new File("output.txt"));
    // hook for closing the stream 
    Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
     // writing
    write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
     "Alo","Ciao");    
     // writing again
    write(printStream, "A new String", "And again another one...");        
}


public static void write(PrintStream printStream, String... values) throws Exception {

  try{                 
     for (String value : values){
       printStream.println(value);
     }
     printStream.flush();
   }
    catch (Exception e){
       // handling exception
   }       
 }

}

关于java - 将所有java输出写入txt文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130712/

相关文章:

java - 如何在泛型类型变量上调用方法

java - 将 ArrayList 中的对象添加到另一个 ArrayList

javascript - ASP.NET 中的选项卡式网站,想要打印所有内容,有推荐吗?

html - CSS 打印预览边距

C 访谈输出

java - "Content-Disposition header"中的配置 "Apache HTTP Server"

java - 与@helper 类型不匹配

R:如何将结果合并为唯一的输出?

azure - 是否可以从 Azure 工作线程进行打印?

javascript - 答案不会显示在消息框中