try-with-resources 文で、PrintWriter pw = new PrintWriter(System.out) を書いて、
try-with-resources文の finally を実行した後ろで、System.out.print を実行しても
既に close しているのだから、print / println は機能しない。
でも、再度、System.out.print . System.out.println が働くようにする方法がある。
java - System.out closed? Can I reopen it? - Stack Overflow
この方法を見て思わず唸ってしまった。
import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; public class UnclosableOutputStream extends FilterOutputStream { public UnclosableOutputStream(OutputStream out) { super(out); } @Override public void close() throws IOException { out.flush(); } }
という、FilterOutputStream 継承して、close() のオーバライドで、flush を代わりに実行する方法だ。
PrintWriter pw = new PrintWriter(new UnclosableOutputStream(System.out)); pw.print(body); pw.close(); System.out.println("test");
見事に、body を標準出力して close() 実行を見せかけて、次に "test" を標準出力する。