How to get the size of an InputStream?

membersound picture membersound · Feb 19, 2016 · Viewed 47.7k times · Source

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());

Answer

user207421 picture user207421 · Feb 19, 2016

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.