我正在尝试将一个存储OutputStream
为一个类的成员,以便我可以从多个方法写入它。我把这个 jUnit 测试放在一起来证明我遇到的问题。
public class XmlStreamWriterTest {
private OutputStream outputStream;
@Before
public void setUp() throws Exception {
File file = new File("xmltester.xml");
this.outputStream = new FileOutputStream(file);
}
@After
public void tearDown() throws Exception {
this.outputStream.close();
}
//This doesn't work.
@Test
public void testOutputStream() throws Exception {
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(this.outputStream);
xmlStreamWriter.writeStartElement("test");
xmlStreamWriter.writeCharacters("This is a test.");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.flush();
}
//This works
@Test
public void testOutputStreamLocal() throws Exception {
File file = new File("xmltester2.xml");
OutputStream outputStreamLocal = new FileOutputStream(file);
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(outputStreamLocal);
xmlStreamWriter.writeStartElement("test");
xmlStreamWriter.writeCharacters("This is a test.");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.close();
}
}
在生成的文件中,只有第二种方法将任何值推送到文件中。我必须直接传递OutputStream
给每个方法吗?为什么testOutputStream()
方法不起作用?
我正在使用 jrockit jdk 1.6.0_29,但我尝试在 JDK 8 上运行,并且效果相同。