Search code examples
javacallbackjaxbsystem.out

How to avoid System.out getting closed from Callback


I want to output the generated schema to the stdout. So I set the System.out as the outputStream of SchemaOutputResolver. StreamResult result = new StreamResult(System.out); But after the statement: jc.generateSchema(outputResolver)

System.out.println() doesn't work anymore. By debugging the code I got that System.out was closed after jc.generateSchema Method.

  JAXBContext jc = JAXBContext.newInstance(SomeObject.class);
  SchemaOutputResolver outputResolver = new SchemaOutputResolver() {

    @Override
    public Result createOutput(String namespaceUri, String suggestedFileName)
        throws IOException {

      StreamResult result = new StreamResult(System.out);

      result.setSystemId(namespaceUri);


      // return result
      return result;
    }
  };
  jc.generateSchema(outputResolver);
  System.out.println("this String can't be output");

My Question is, how to output the generated schema to stdout without closing the System.out by using jc.generateSchema?


Solution

  • Create a PrintStream class (say, UncloseablePrintStream) that just wraps another PrintStream and ignores the close call, then do:

    StreamResult result = new StreamResult(new UncloseablePrintStream(System.out)));
    

    Completely untested, but it may be this simple:

    import java.io.PrintStream;
    
    public class UncloseablePrintStream extends PrintStream {
        public UncloseablePrintStream(PrintStream ps) {
            super(ps);
        }
    
        @Override
        public void close() {
            // Do nothing
        }
    }