2016-05-31 30 views
0

嗨,我無法在關閉PrintWriter後添加新的內容。有沒有其他的方式來做到這一點。關閉PrintWriter後無法寫入新的HTML內容

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"); 
+2

爲什麼你需要關閉它在中間? – stdunbar

+0

爲什麼你認爲在關閉它之後你仍然可以寫內容? –

回答

2

流生命週期是:

  1. Createtion(new Stream
  2. 處理(writeappend,等等)
  3. 結算(close

PrintWriter::close() DOC:

關閉流並釋放與其關聯的任何系統資源 。

PrintWriter::close()out = null裏面PrintWriter。 關閉之後,您將在writeflush,print等等的任何呼叫處獲得IOException。 這些方法在執行任何操作之前都會調用ensureOpen()

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

謝謝你的解釋謝爾蓋Rybalkin –