Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of an InputStream? [duplicate]

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());
like image 467
membersound Avatar asked Feb 19 '16 09:02

membersound


People also ask

Can I read InputStream twice?

Don't read it twice. Save the result in a data structure.

How do you read all bytes from InputStream?

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.

How does InputStream read () method work?

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.


1 Answers

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.

like image 153
user207421 Avatar answered Nov 01 '22 07:11

user207421