簡體   English   中英

如何重構用Java關閉流?

[英]How do I refactor closing a stream in Java?

由於我公司使用Eclipse並使用Eclipse的代碼自動修復的政策,以下代碼模式在代碼庫中過多出現:

InputStream is = null;
try {
    is = url.openConnection().getInputStream();
    // .....
} catch (IOException e) {
    // handle error
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
            // handle error
       }
    }
}

IMO非常丑陋且難以閱讀,尤其是finally塊中的部分(確實需要捕獲2個IOException實例嗎?)。 無論如何,是否有必要簡化代碼以使其看起來更干凈?

為什么要做什么? 它是工作代碼。 這是正確的。

隨它去吧。

看到這個問題 ,使用closeQuietly()解決方案。

InputStream is = null;
try {
    is = url.openConnection().getInputStream();
    // .....
} catch (IOException e) {
    // handle error
} finally {
    IoUtils.closeQuietly(is);
}

// stolen from the cited question above
public class IoUtils {

  public static closeQuietly (Closeable closeable) {
    try {
      closeable.close();
    } catch (IOException logAndContinue) {
      ...
    }
  }
}

或等待JDK7的ARM模塊

首先,關於使用IOUtils可能需要告訴您的主管,他們可能會使用的應用程序服務器/ Java運行時環境本身使用IOUtils和類似的庫。 因此,從本質上講,您並不是在架構中引入新組件。

第二,不,不是真的。 除了編寫自己的模仿IOUtils的closeQuietly方法的實用程序外,實際上沒有任何其他closeQuietly方法。

public class Util {
    public static void closeStream(inputStream is) {
        if (is != null) {
            try {
               is.close();
            } catch (IOException e) {
               // log something
        }
    }
}

現在你的代碼是

InputStream is = null;
try {
    is = url.openConnection().getInputStream();
    // .....
} catch (IOException e) {
    // handle error
} finally {
    Util.closeStream(is);
}

沒有太多其他事情要做,因為捕獲中的IOException可能有一些特定的處理。

您可以在某處定義這樣的內容:

private static interface InputStreamCallback {

    public void doIt(InputStream is) throws IOException;

}

private void with(InputStreamCallback cb) {

    InputStream is = null;

    // Creational code. Possibly adding an argument

    try {
        cb.doIt(is);
    } catch (IOException e) {
        // handle error or rethrow.
        // If rethrow add throws to method spec.
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // handle error or rethrow.
            }
        }
    }
}

並像這樣調用您的代碼:

with(new InputStreamCallback() {

    @Override
    public void doIt(InputStream is) throws IOException {
        is = url.openConnection().getInputStream();
        // .....
    }

});

如果在幫助程序類中使用static方法聲明,則甚至可以對其進行import static

有一個缺點。 您需要聲明url final。

編輯:創建代碼不是重點。 您可以通過幾種方式進行安排。 回調是重點。 您可以在此處隔離需要執行的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM