-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?

bbbot
  • 23
  • 2
  • 6
  • 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? – Duncan Jones Sep 10 '14 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 – bbbot Sep 10 '14 at 10:10
  • You cannot get the size without loading it. – afzalex Sep 10 '14 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](http://stackoverflow.com/q/1264709). You've earned a down-vote from me, because this is an easily researched topic. – Duncan Jones Sep 10 '14 at 10:12

2 Answers2

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

Westranger
  • 1,308
  • 19
  • 29
  • 2
    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](http://stackoverflow.com/a/1264737/592139) which uses bulk read and write via a temporary fixed size buffer. – Ian Roberts Sep 10 '14 at 10:36
-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]

 }
Rafa Romero
  • 2,667
  • 5
  • 25
  • 51
  • if I read it like this, where the data will be putted if there are not byte buffer param? – bbbot Sep 10 '14 at 10:04
  • This reads one byte, and returns one byte. I don't think it's what you wanted. – user253751 Sep 10 '14 at 10:04
  • This is completely wrong. This reads one byte from the input stream. – Duncan Jones Sep 10 '14 at 10:04
  • I have edited the answer. I have not expressed well. I forgot to add the loop – Rafa Romero Sep 10 '14 at 10:06
  • @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 – bbbot Sep 10 '14 at 10:09
  • **You code is still wrong**. `len` implies a length is returned, when in fact a byte value from the stream is returned. And you could really do with indicating what `[your code]` is supposed to be. I honestly don't know how this got 3 up-votes - amazing. – Duncan Jones Sep 10 '14 at 13:55