標準出力のバンドル FileDescriptor.out で戻せば良い。
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
例)ファイルに書いていて、元に戻す。
try(FileOutputStream fo = new FileOutputStream(new File("/work/test.txt"))){ System.setOut(new PrintStream(fo)); // 標準出力は、File("/work/test.txt") に出力される。 }catch(IOException e){ e.printStackTrace(); } // 元に戻す System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
try-with-resources を書かずに、ByteArrayOutputStream に書き出す。
ByteArrayOutputStream bo = new ByteArrayOutputStream(); System.setOut(new PrintStream(bo)); System.out.println("この出力は、ByteArrayOutputStream"); System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); try{ bo.close(); }catch(IOException e){} System.out.println("after"); System.out.println(bo.toString());
実行結果は、、
after この出力は、ByteArrayOutputStream