I am writing an app for android which uses InputStream from Socket. I am trying to send a file from pc to android this way. The size of the file is almost 40kb and on android I am finding that it is able to read only 2kb of data at a time so I am reading 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;
}
}
Form these 2 methods which will be faster in terms of performance?
The second, potentially by a long way. Reading a block at a time is almost always preferable to reading a byte at a time, unless you really only want to read a single byte anyway.
However, your code is currently broken, in that you don’t take account of the return value of
readother than to check that something has been read. It may not have read 2048 bytes. You should use something like:With this code in place, you may well be able to read more than 2K at a time safely in some situations… it depends on the network, but at least the code will be reliable.