簡體   English   中英

是否可以在不關閉流的情況下關閉Reader?

[英]Is it possible to close a Reader without closing the stream?

我有一個接受InputStream (二進制數據)並將其序列化為XML的方法。 為了做到這一點,它使用base64編碼器和Reader包裝流,將其轉換為字符數據。 但是,由於InputStream作為參數傳入,我認為關閉流是一個有害的副作用,而Reader.close()的合同說它會這樣做。 如果我不關閉閱讀器,編譯器警告我,我有一個

資源泄漏:讀者永遠不會關閉

所以,我可以在讀者聲明中添加@SuppressWarnings( "resource" ) ,但這是正確的做法嗎? 我錯過了什么嗎?

這是實際的代碼:

/**
 * Writes base64 encoded text read from the binary stream.
 * 
 * @param binaryStream
 *            The binary stream to write from
 * @return <code>this</code> XmlWriter (for chaining)
 * @throws IOException
 */
public XmlWriter binary( InputStream binaryStream ) throws IOException {
    Reader reader = new InputStreamReader( 
            new Base64InputStream( binaryStream, true, base64LineLength, base64LineSeparator.getBytes( charset ) ) );
    int bufferSize = 2048;
    int charsRead;
    char[] buffer = new char[bufferSize];
    while ( (charsRead = reader.read( buffer, 0, bufferSize )) >= 0 ) {
        writer.write( buffer, 0, charsRead );
    }

    return this;
}

如果您是一個快樂的Java 7用戶,請嘗試以下方法:

try(InputStream binaryStream = /* ... */) {
    xmlWriter.binary(binaryStream);
}

並且流為您關閉。 如果你不能使用Java 7,我同意close()流的binary()方法不是責任。 只需忽略警告,不要讓工具驅動您的設計。 沒關系。

作為最后的手段,你可以寫一個輕量級的Reader包裝器忽略close() ,但我不建議它,因為它使程序流更難。

也讓Apache Commons IO幫助您使用IOUtils.copy()

public XmlWriter binary( InputStream binaryStream ) throws IOException {
    Reader reader = new InputStreamReader( 
            new Base64InputStream( binaryStream, true, base64LineLength, base64LineSeparator.getBytes( charset ) ) );
    IOUtils.copy(reader, writer);
    return this;
}

這可能是Base64InputStream工作方式中的一個“特性”,即使您指定要讀取的長度,如果您關閉它,它會關閉它,顯然您打算不讀取整個流。

您可以將binaryStream包裝在一個忽略關閉的InputStream中,或者您可以按原樣抑制警告。

暫無
暫無

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

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