在得知OP要复制流后更新了答案
由于要在两个流中写入数据,请尝试
TeeOutputStream从Apache
Commons使用。再次尝试更改代码
try { FileOutputStream fos = new FileOutputStream(f); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { fos.flush(); } catch (Throwable t) { // Ignore } }, "Shutdown hook Thread flushing " + 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也将放入您的文件中。



