我有一个由另一个OutputStream支持的CipherOutputStream。在我将所有需要加密的数据写入CipherOutputStream后,我需要附加一些未加密的数据。
The documentation for CipherOutputStream表示调用flush()
不会强制最终阻止加密器;为此,我需要致电close()
。但是close()
也会关闭底层的OutputStream,我还需要写更多内容。
如何在不关闭流的情况下强制最后一个块退出加密器?我是否需要编写自己的NonClosingCipherOutputStream?
答案 0 :(得分:8)
如果您没有Cipher
的引用,则可以将FilterOutputStream
传递给创建CipherOutputStream
的方法。在FilterOutputStream
中,覆盖close
方法,以便它实际上不会关闭流。
答案 1 :(得分:1)
也许你可以在输入cipheroutputstream之前包装你的输出流
/**
* Represents an {@code OutputStream} that does not close the underlying output stream on a call to {@link #close()}.
* This may be useful for encapsulating an {@code OutputStream} into other output streams that does not have to be
* closed, while closing the outer streams or reader.
*/
public class NotClosingOutputStream extends OutputStream {
/** The underlying output stream. */
private final OutputStream out;
/**
* Creates a new output stream that does not close the given output stream on a call to {@link #close()}.
*
* @param out
* the output stream
*/
public NotClosingOutputStream(final OutputStream out) {
this.out = out;
}
/*
* DELEGATION TO OUTPUT STREAM
*/
@Override
public void close() throws IOException {
// do nothing here, since we don't want to close the underlying input stream
}
@Override
public void write(final int b) throws IOException {
out.write(b);
}
@Override
public void write(final byte[] b) throws IOException {
out.write(b);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
out.write(b, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
}
希望有所帮助
答案 2 :(得分:0)
如果你引用Cipher
包裹的CipherOutputStream
对象,你应该可以执行CipherOutputStream.close()
所做的事情:
调用Cipher.doFinal,然后调用flush()
CiperOutputStream,然后继续。