Java console output into the file saved

Foreword

Implemented in the console output and the output into a file saved

achieve

You want to write data in two streams, try using OutputStreamtheTeeOutputStream对象。

 

First, the package is introduced in the maven pom jar file.

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6.0</version>
     </dependency>

 

Second, manually download jar package.

Download Path: http://us.mirrors.quenda.co/apache//commons/io/binaries/commons-io-2.6-bin.zip

 

Third, the implementation code.

try {
    FileOutputStream fos = new FileOutputStream(f);//f:生成的文件路径
    //we will want to print in standard "System.out" and in "file"
    TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
    PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
    System.setOut(ps);
} catch (Exception e) {
    e.printStackTrace();
}
System.out.print("123456789");

 

Guess you like

Origin www.cnblogs.com/nhdlb/p/11599500.html