Java:Java控制台输出保存进文件

前言

实现在控制台输出、并且把输出保存进文件

实现

您要在两个流中写入数据,请尝试使用OutputStream中的TeeOutputStream对象。

 

一、在maven的pom文件中引入jar包。

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

 

二、手动下载jar包。

下载路径:http://us.mirrors.quenda.co/apache//commons/io/binaries/commons-io-2.6-bin.zip

 

三、实现代码。

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");
posted @ 2019-09-27 17:55  怒吼的萝卜  阅读(1961)  评论(0编辑  收藏  举报