Search code examples
javaoutputstreamfileoutputstreambytearrayoutputstream

Java: I need to get byte array out of outputstream


In my case the out put stream is basically FileOutputStream. Hence for this code:

ByteArrayOutputStream bos = (ByteArrayOutputStream) streamToEncrypt;

(Where streamToEncrypt is OutputStream) is getting this exception:

java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to java.io.ByteArrayOutputStream

All I need to do is to get the byte array out of this outputstream. I do NOT have access to the file at this level. All I have is this output stream that I have to encrypt before pushing it to the file


Solution

  • You don't get bytes out of an OutputStream. You get them out of an InputStream. You put bytes into an OutputStream.

    If bytes have already been written to the OutputStream, it's too late. Opening the file again and reading from it is the only way for you to access those data.

    If you want to encrypt an output stream, you should construct the stream and pass it to the code that writes to the stream.

    Cipher enc = Cipher.getInstance("...");
    enc.init(...);
    try (OutputStream fos = Files.newOutputStream(path);
         OutputStream os = new CipherOutputStream(fos, enc)) {
       writingObject.write(os);
    }