在txt文件中编写所有java输出

时间:2016-12-13 21:18:29

标签: java printing output bufferedreader printwriter

我想知道如何在.txt文件中编写java输出中的所有行 到目前为止我已经完成了一些测试,但我似乎无法找到解决方案:/
这是一个小代码,如果你能告诉我这个,我将不胜感激: 下面显示的代码询问用户在.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();
    }

}

2 个答案:

答案 0 :(得分:1)

直接使用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
   }       
 }

}

答案 1 :(得分:0)

java test.Test > somefile.txt