An InputStream that reads faster () or reads (byte, offset, length)

I am writing an Android application that uses InputStreamfrom Socket. I am trying to send a file from a computer to android in this way. The file size is almost 40 kbytes, but on Android I found that it is able to read only 2 kbytes of data at a time, so I read it in chunks.

I have two methods for reading bytes

1)

while((d=inputStream.read())>=0)
{
    imgData[i]=(byte)d;
    i++;
    if(i>=40054)
    {
        // do the further processing here like saving it on disk.
        i=0;
    }
}

2)

while(inputStream.read(byte,0,2048)>=0)
{
    //merge this byte to buffer here... 
    i=i+2048;
    if(i>=40054)
    {
        // do the further processing here like saving it on disk.
        i=0;
    }
}

Build these 2 methods that will be faster in terms of performance?

+3
source share
2 answers

The second, potentially long way. Reading a block at a time is almost always preferable to reading a byte at a time, unless you really want to read one byte anyway.

, read, , - . , 2048 . - :

int bytesRead;

while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0)
{
    // Use bytesRead here
}

2K ... , , , .

+7

@Op, BufferedInputStream chuncks .

0

All Articles