2016-12-16 62 views
2

我是否需要單獨定義Binary對象,以便我可以調用.dispose();(請參閱methodOne()),或者在自動關閉InputStream時自動處理它(請參閱methodTwo())?我是否需要調用.dispose()(javax.jcr.Binary)和.close()(java.io.InputStream)?

private void methodOne(Resource resource) { 
    Binary binary = resource.getValueMap().get("jcr:data", Binary.class); 
    try { 
     InputStream is = null; 
     try { 
      is = binary.getStream(); 
      // ...do something with the InputStream... 
     } catch (RepositoryException e) { 
      LOG.error("RepositoryException trying to get an InputStream from the resource."); 
     } finally { 
      if (is != null) { 
       IOUtils.closeQuietly(is); 
      } 
     } 
    } finally { 
     binary.dispose(); 
    } 
} 

private void methodTwo(Resource resource) { 
    try (InputStream is = resource.getValueMap().get("jcr:data", Binary.class).getStream()) { 
     // ...do something with the InputStream... 
    } catch (IOException e) { 
     LOG.error("IOException from trying to auto-close InputStream."); 
    } catch (RepositoryException e) { 
     LOG.error("RepositoryException trying to get an InputStream from the resource."); 
    } 
} 

我如何如果methodTwo匿名二進制資源正在被妥善處置,這就是爲什麼我甚至要求在第一時間這個問題,甚至測試真正困惑。

回答

4

除非您從關閉流的文檔中獲取流的類已足夠,否則您需要確保您列出try中的其他可關閉資源,以便try-with-resources爲您關閉它們。

你說過Binary沒有執行AutoCloseable。刺激。 :-)你總是可以定義一個包裝(如我想這不僅是你需要對付這種地方),東西沿着這些線路:

public class ACBinaryWrapper implements AutoCloseable { 
    private Binary binary; 

    public ACBinaryWrapper(Binary binary) { 
     this.binary = binary; 
    } 

    public Binary getBinary() { 
     return this.binary; 
    } 

    public void close() { 
     if (this.binary != null) { 
      Binary b = this.binary; 
      this.binary = null; 
      b.dispose(); 
     } 
    } 
} 

然後:

private void yourMethod(Resource resource) { 
    try (
     ACBinaryWrapper acbinary = new ACBinaryWrapper(
      resource.getValueMap().get("jcr:data", Binary.class) 
     ); 
     InputStream is = acbinary.getBinary().getStream(); 
    ) { 
     // ...do something with the InputStream... 
    } catch (IOException e) { 
     // ...appropriate handling... 
    } catch (RepositoryException e) { 
     // ...appropriate handling... 
    } 
} 

binaryis分開列出。


你在IOException處理LOG語句和這樣似乎認爲,關閉流時可能發生的唯一的I/O錯誤了。一般來說,從流中讀取也會導致I/O錯誤。

+0

非常感謝您對IOException處理的澄清以及快速回答! javax.jcr.Binary不擴展Closeable或AutoCloseable,因此在try-with-resources聲明中聲明它不一定會處理對'.dispose();'的調用,對吧? – Gdubz

+1

@gdubz:對不起,我的錯誤,我認爲它是'AutoCloseable'。一秒鐘...... –

+0

這很好。讀取類中的註釋,聽起來像我負責調用InputStream上的'.close()'和Binary對象上的'.dispose()'。我只是不清楚調用'.getStream()'關閉鏈式初始化(​​我猜將一個匿名Binary對象留在那裏?),或者甚至如何測試/調試它。 – Gdubz

相關問題