如何强制CipherOutputStream完成加密但保持底层流打开?
我有一个由另一个OutputStream支持的CipherOutputStream。 在我将所有需要加密的数据写入CipherOutputStream后,我需要附加一些未加密的数据。
CipherOutputStream的文档说调用flush()
不会强制最后一个块脱离加密器; 为此,我需要调用close()
。 但是close()
也会关闭底层的OutputStream,我仍然需要写更多内容。
如何在不关闭流的情况下强制最后一个块离开加密器? 我是否需要编写自己的NonClosingCipherOutputStream?
如果您没有对Cipher
的引用,则可以将FilterOutputStream
传递给创建CipherOutputStream
的方法。 在FilterOutputStream
,重写close
方法,使其实际上不关闭流。
也许你可以在输入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(); } }
希望有所帮助
如果您对CipherOutputStream
包装的Cipher
对象有引用,那么您应该能够执行CipherOutputStream.close()
执行的操作:
调用Cipher.doFinal ,然后flush()
CiperOutputStream,并继续。