如何避免System.out从Callback中关闭

时间:2016-07-15 15:16:55

标签: java callback jaxb system.out

我想将生成的架构输出到stdout。所以我将System.out设置为SchemaOutputResolver的outputStream。 StreamResult result = new StreamResult(System.out); 但声明后: jc.generateSchema(outputResolver)

System.out.println()不再起作用了。通过调试我得到的代码,System.out在jc.generateSchema方法之后关闭了。

  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");

我的问题是,如何使用jc.generateSchema将生成的架构输出到stdout而不关闭System.out?

2 个答案:

答案 0 :(得分:1)

创建一个Collectors.toMap()类(例如,PrintStream),只包装另一个UncloseablePrintStream并忽略PrintStream调用,然后执行:

close

完全未经测试,但可能很简单:

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

答案 1 :(得分:1)

您可以打印到ByteArrayOutputStream,然后根据需要使用它:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
StreamResult result = new StreamResult(ps);
System.out.println(new String(baos.toByteArray(), StandardCharsets.UTF_8));

result.setSystemId(namespaceUri);