Java – faster read () or read (byte, offset, length) InputStream
I am writing an application using socket InputStream for Android I tried to send files from my PC to Android in this way The size of the file is almost 40KB. On Android, I found that it can only read 2KB of data at a time, so I'm reading it in blocks
I have two ways to read 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,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; } }
Will these two methods be faster in terms of performance?
Solution
Second, it may be a long way to go Reading one block at a time is almost always better than reading one byte at a time, unless you really want to read only one byte
However, your code is currently corrupted because you do not consider the read return value other than checking the read content It may not have read 2048 bytes You should use something similar:
int bytesRead; while ((bytesRead = inputStream.read(buffer,buffer.length)) > 0) { // Use bytesRead here }
With this code, you can safely read more than 2K data in some cases... It depends on the network, but at least the code is reliable