I'm having an InputStream
from a ProcessBuilder
that acutally reads the stdout
stream.
Question: how can I know the size of that inmemory InputStream
, so I can write it to a HttpResponse
http header?
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream out = response.getOutputStream();
int bytes;
while ((bytes = br.read()) != -1) {
out.write(bytes);
}
//how can I know the size of the inmemory stream/file written?
//response.setContentLength((int) pdfFile.length());
Don't read it twice. Save the result in a data structure.
Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.
read. Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255 . If no byte is available because the end of the stream has been reached, the value -1 is returned.
There is no such thing as the size of an input stream. Consider a program which never exits, or a socket peer which never stops sending. And you don't need to know to write it to an HttpResponse
header. The Content-length
is managed automatically for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With