![](/img/trans.png)
[英]SSLSocket client doesn't throw exception if server is shutdown when writing to OutputStream
[英]When OutputStream is stored as a member, it doesn't seem to work when writing to it using an XmlStreamWriter, can it not be passed as a member?
我试图将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上运行,但效果相同。
如果您在调试器中逐步执行此测试,并在每个测试的“刷新/关闭”(即最后一个)行上设置一个断点,那么当您越过它时,可以看到在两种情况下均已写入文件。
问题是您的设置方法。
这就是正在发生的事情...
基本上,将代码从设置方法中移出到第一个测试用例中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.