java - 关闭 PrintWriter 后无法写入新的 HTML 内容

标签 java

<小时/>

您好,关闭 PrintWriter 后无法添加新内容。还有其他方法可以做到这一点吗?

String myCurrentDir = System.getProperty("user.dir");
File htmlFile = new File(TestRunner.FilePath+"\\Footer.html");
final OutputStream out = new BufferedOutputStream(new FileOutputStream(htmlFile));
PrintWriter writer = new PrintWriter(out);
writer.println("<HTML>");       
writer.println("<HEAD>");
writer.println("<title>Report Foot</title>");
writer.println("<link rel=\"stylesheet\" type=\"text/css\" href=\""+myCurrentDir+"/CSS/Report.CSS\">");
writer.println("</HEAD>");
writer.println("<body class = 'footer'>");
writer.println("<B>");
writer.println("Total : "+TotalTCs);
writer.println("<span class='passed'>Passed : "+0+"</span>");
writer.println("<span class='failed'>Failed : "+0+"</span>");
writer.println("<span class='warned'>Warned : "+0+"</span>");
writer.println("<span class='norun'>No Run : "+0+"</span>");
writer.println("</B>");
writer.println("<BR/>");
writer.println("<BR/>");
writer.close();//after this any content doesn't gets saved in html      
writer.println("@ABC DEF XYZ");
writer.println("</body>");
writer.println("</HTML>");
writer.close();
System.out.println("Footer Written");

最佳答案

流的生命周期是:

  1. 创建(新流)
  2. 处理(写入追加等)
  3. 关闭(关闭)

来自 PrintWriter::close() 文档:

Closes the stream and releases any system resources associated with it.

PrintWriter::close()PrintWriter 内设置 out = null。 关闭后,您将在任何调用 writeflushprint 等时得到 IOException。 这些方法在执行任何操作之前都会调用 ensureOpen()

private void ensureOpen() throws IOException {
    if (out == null)
        throw new IOException("Stream closed");
    }
}

关于java - 关闭 PrintWriter 后无法写入新的 HTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548601/

相关文章:

java - 如何用 mockito 模拟 builder

java - 无法用maven编译java项目

java - TabLayout setText() 和 setIcon() 无法与自定义 View 一起正常工作

java - 为数组赋值

java - 部署到 Tomcat 后填充下拉列表不起作用

java - 制作一个迷你口袋妖怪项目,我需要独特的类(class)?

java - 何时以及如何使用 hibernate 二级缓存?

java - 同时比较二维数组的层

java - 强制 Java 运行时在 NSF 中使用 Jar 而不是在 XPages 应用程序的同名服务器上使用 Jar

java - 无法从 START_OBJECT token 中反序列化 java.lang.Class 的实例