0

在我的应用程序中,我遇到了一个问题,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"

4

1 回答 1

0

解决方案是我没有设置编码类型。或者他们以某种方式有所不同。当我将编码设置为 UTF-8 时,文件被写入就好了:

xmlOutputFactory.createXMLStreamWriter(this.getOutputStream(), "UTF-8");

我发现这一点是因为当我在 IntelliJ 中设置 maven 目标时,该开关-Dfile.encoding=UTF-8将附加到 mvn 命令的末尾,然后测试将正确构建 XML 文件。

于 2015-02-09T20:47:29.073 回答