-1
byte[] b = new byte[10000];
len = readerIn.read(b); // InputStream

My byte size is 10000, but the InputStream size may be lower or higher. Is there a way to read only the size of data that comes into the InputStream?

4
  • Are you asking how to read an input stream completely into a byte array of the correct length? Or do you just want to know the size of the stream, without reading it? Commented Sep 10, 2014 at 10:07
  • @Duncan yes I want to read the correct size, the exact size, no more or less into the byte array, or any other class that can help me save the readed bytes Commented Sep 10, 2014 at 10:10
  • You cannot get the size without loading it. Commented Sep 10, 2014 at 10:12
  • Grrrrrr, you edited your comment just as I closed as a duplicate to a different question. The correct duplicate is: Convert InputStream to byte array in Java. You've earned a down-vote from me, because this is an easily researched topic. Commented Sep 10, 2014 at 10:12

2 Answers 2

0

You can use the ByteArrayOutputStream for this

ByteArrayOutputStream baos = new ByteArrayOutputStream();
int reads = is.read();

while(reads != -1){
    baos.write(reads);
    reads = is.read();
}

byte[] data = baos.toByteArray();

the data array has the proper size and contains all the data of or InputStream

Sign up to request clarification or add additional context in comments.

1 Comment

Reading and writing one byte at a time will be very very inefficient, particularly if the incoming stream is not internally buffered. Much better would be this answer from the linked duplicate question which uses bulk read and write via a temporary fixed size buffer.
-1

You can read the totally size of data reading byte by byte by no putting paramenter in read method:

len = readerIn.read();

You can readstill the end of the stream

 while((readerIn.read())!=-1){

     [your code]

 }

6 Comments

if I read it like this, where the data will be putted if there are not byte buffer param?
This reads one byte, and returns one byte. I don't think it's what you wanted.
This is completely wrong. This reads one byte from the input stream.
I have edited the answer. I have not expressed well. I forgot to add the loop
@RafaRomero one more question, how can I read it without explicitly indicate the size byte[] = new byte[1024], I wished to make it dynamic, but here I have to create this byte array again
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.