我正在为 android 编写一个应用程序,它使用 Socket
中的 InputStream
。我正在尝试通过这种方式将文件从 pc 发送到 android。该文件的大小将近 40kb,在 android 上我发现它一次只能读取 2kb 的数据,所以我正在分块读取它。
我有两种读取字节的方法
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;
}
}
形成这两种方法哪个在性能方面会更快?
最佳答案
第二个,可能还有很长的路要走。一次读取一个 block 几乎总是比一次读取一个字节更可取,除非您真的无论如何只想读取一个字节。
但是,您的代码目前已损坏,因为您没有考虑 read
的返回值,只是检查是否已读取某些内容。它可能没有读取 2048 个字节。你应该使用类似的东西:
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0)
{
// Use bytesRead here
}
有了这段代码,在某些情况下,您可以一次安全地读取超过 2K 的内容……这取决于网络,但至少代码是可靠的.
关于java - InputStream 哪个更快 read() 或 read(byte,offset,length),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919818/