我目前在java中做這樣的事情來釋放資源。我是否需要在BufferedWriter對象上調用close或在析構函數中調用它?關於Resource1和Resource2,我必須致電發佈和免費。這是嵌套式的正確方法嗎? Python有一個非常好的「聲明」,它將資源與代碼範圍相關聯。 java有喜歡嗎?在Java中關閉資源
Resource1 r1 = new Resource1();
try
{
...
Resource2 r1 = new Resource2();
try
{
...
java.io.BufferedWriter f = new java.io.BufferedWriter(new java.io.FileWriter(new java.io.File("f")));
try
{
...
}
finally
{
f.close();
}
}
finally
{
r2.release();
}
}
finally
{
r1.free();
}
UPDATE: 我使用Java 1.6
Java 7已經嘗試使用資源特性,從您的問題中不清楚您使用的是哪個java版本http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources。 html – kosa
[How to Correctly Close Resources](http://stackoverflow.com/questions/5782647/how-to-correctly-close-resources) – djechlin
請先Google。 – djechlin