1. 程式人生 > >SAXBuilder不釋放檔案控制代碼的問題

SAXBuilder不釋放檔案控制代碼的問題

參考:

問題描述:

有人報告 SAXBuilder 存在bug:開啟檔案後並不釋放檔案資源,結果多次開啟同一個檔案後,會導致”too many open files“錯誤。

解決:

將下面的做法

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(path);
Document document = (Document) builder.build(xmlFile);

改成這樣
InputStream xmlFile = null;
try {
	SAXBuilder builder = new SAXBuilder();
	xmlFile = new FileInputStream(your_file_path);
	Document document = (Document) builder.build(xmlFile);
} catch (...) {
	...
} finally {
	try {
		xmlFile.close();
	} catch (IOException e) {
		...
	}
}
即,在finally 程式碼塊中,強制釋放檔案資源。