How can we read or use the contents of outputstream
java, servlets
Solution
How can we read or use the contents of outputstream.
In general you can't. An `OutputStream` is an object that you write bytes to. The general API doesn't provide any way to get the bytes back.
There are specific kinds of output stream that would allow you to get the bytes back. For instance:
- A `ByteArrayOutputStream` has a method for getting the byte array contents.
- A `PipeOutputStream` has a corresponding `PipeInputStream` that you can read from.
- If you use a `FileOutputStream` to write to file, you can typically open a `FileInputStream` to read the file contents ... provided you know the file pathname.
Looking at that method, it strikes me that the method signature is wrong for what you are trying to do. If the purpose is to provide an encrypter for a stream, then the method should return an `InputStream`. If the purpose is to write the encrypted data somewhere, then the method should return `void` and take an extra parameter that is the `OutputStream` that the method should write to. (And then the caller can use an `OutputStream` subclass to capture the encrypted data ... if that is what is desired.)
Another alternative that would "work" is to change the method's signature to make the return type `ByteArrayOutputStream` (or a file name). But that is not a good solution because it takes away the caller's ability to decide where the encrypted output should be sent.
UPDATE
Regarding your solution
OutputStream os = AESHelper.decryptAsStream(sourceFile, encryptionKey);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos = (ByteArrayOutputStream) os;
byte[] imageBytes = baos.toByteArray();
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
OutputStream outs = response.getOutputStream();
outs.write(imageBytes);
That could work, but it is poor code:
If `AESHelper.decryptAsStream` is a method that you wrote (and it looks like it is!), then you should declare it as returning a `ByteArrayOutputStream`.
If it is already declared as returning a `ByteArrayOutputStream` you should assign it directly to `baos`.
Either way, you should NOT initialize `baos` to a newly created `ByteArrayOutputStream` instance that immediately gets thrown away.
It is also worth noting that the Content-Type is incorrect. If you sent that response to a browser, it would attempt to interpret the encrypted data as an image ... and fail. In theory you could set a Content-Encoding header ... but there isn't one that is going to work. So the best solution is to send the Content-Type as "application/octet-stream".
Problem
How can we read or use the contents of outputstream. In my case, I am using a method having signature. public static OutputStream decryptAsStream(InputStream inputStream, String encryptionKey) This method return OutputStream. I want get OutputStream to String. Is it possible to pipe the output from an java.io.OutputStream to a String in Java?