在我的应用程序中,我遇到了一个问题,OutputStream
当我运行“mvn clean test”时,它没有向文件写入任何内容,但是当我通过右键单击运行 testWritingToFile() 在 IntelliJ 中运行它时,它工作正常并输出到文件。
我有以下测试:
@Test
public void testWritingToFile() throws Exception {
File fileXml = new File("xmltest.xml");
OutputStream outputStream = new FileOutputStream(fileXml);
XmlStreamWriting xmlStreamWriting = new XmlStreamWriting(outputStream);
xmlStreamWriting.writeXmlToStream();
outputStream.close();
}
这是我从测试中调用的类(XmlStreamWriting.java):
public class XmlStreamWriting extends XmlStreamWritingBase {
public XmlStreamWriting(OutputStream outputStream) {
this.setOutputStream(outputStream);
}
public void writeXmlToStream() throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = this.getXmlStreamWriter();
xmlStreamWriter.writeStartElement("test");
xmlStreamWriter.writeCharacters("This is a test.");
xmlStreamWriter.writeEndElement(); //test
}
}
这是它扩展的抽象类(XmlStreamWritingBase.java):
public abstract class XmlStreamWritingBase {
private XMLStreamWriter xmlStreamWriterPrivate;
private OutputStream outputStream;
public XMLStreamWriter getXmlStreamWriter() throws XMLStreamException {
if(xmlStreamWriterPrivate == null) {
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
xmlStreamWriterPrivate = xmlOutputFactory.createXMLStreamWriter(this.getOutputStream());
}
return this.xmlStreamWriterPrivate;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
}
如果这很重要,我正在使用 jrockit jdk 1.6.0_29。IntelliJ 和 Maven 都设置为运行该 JDK。
我必须直接传递OutputStream
给每个方法吗?为什么writeXmlToStream()
方法不起作用?
编辑:也只是为了验证流在两种情况下都有效,我将测试更改为这个,当我从 maven 运行时,Test1 和 Test2 之间没有内容,但是当我使用 IntelliJ 运行时,xml 出现在两个字符串之间:
public void testWritingToFile() throws Exception {
File fileXml = new File("xmltest.xml");
OutputStream outputStream = new FileOutputStream(fileXml);
outputStream.write("Test1".getBytes());
XmlStreamWriting xmlStreamWriting = new XmlStreamWriting(outputStream);
xmlStreamWriting.writeXmlToStream();
outputStream.write("Test2".getBytes());
outputStream.close();
}
maven 的输出是 " Test1Test2
",IntelliJ "Run" 的输出是 " Test1<test>This is a test.</test>Test2
"