Java之應何時調用close()方法?

在Java中對資源的讀寫最後要進行close操作,那麼應該放在try還是finally中呢?以下是三種處理方式:

第1種:把close()放在try中

try {
			PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(
					"out.txt", true)));
			pw.println("This is a test.");
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

第2種:把close()放在finally中

PrintWriter pw = null;
		try {
			pw = new PrintWriter(
			   new BufferedWriter(
			   new FileWriter("out.txt", true)));
			pw.println("This is a test.");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(pw != null) {
				pw.close();
			}
		}

第3種:使用try-with-resource語句

try (PrintWriter pw = new PrintWriter(
				            new BufferedWriter(
				            new FileWriter("out.txt", true)))) {
			pw.println("This is a test.");
		} catch (IOException e) {
			e.printStackTrace();
		}

        那麼哪一種方法是對的或者說是最好的呢?

        無論是否有異常發生close()方法都應該被調用,因此close()應放在finally中。而從Java 7開始,可以使用try-with-resource語句。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章