當使用Java InputStreams時,我對使用close()方法有一些疑問。從我看到並從大多數開發人員那裏閱讀的內容中,當不再需要時,您應該始終在InputStream上顯式調用close()。但是,今天我一直在尋找到使用Java屬性文件,我發現每個實例有這樣的事情:關閉Java InputStreams
Properties props = new Properties();
try {
props.load(new FileInputStream("message.properties"));
//omitted.
} catch (Exception ex) {}
通過上面的例子,有沒有辦法來明確調用close(),因爲InputStream爲使用後無法訪問。我已經看到了InputStream的許多類似用法,儘管它似乎與大多數人關於明確關閉的內容相矛盾。我通過Oracle的JavaDocs閱讀,並沒有提到Properties.load()方法是否關閉了InputStream。我想知道如果這通常是可以接受的,或者最好是做一些更類似如下:
Properties props = new Properties();
InputStream fis = new FileInputStream("message.properties");
try {
props.load(fis);
//omitted.
} catch (Exception ex) {
//omitted.
} finally {
try {
fis.close();
} catch (IOException ioex) {
//omitted.
}
}
哪種方式更好和/或更有效?還是它真的很重要?
感謝大家爲你提供的答案。我希望我能接受他們所有的答案。這對我來說很有意義。 – 2010-10-21 20:59:42