套接字read()inputstream的两个例子。哪个更好?

时间:2013-09-26 23:29:51

标签: java android sockets networking tcp

这里显示的是关于如何在socketStream中读取套接字连接的两个代码示例,其中哪些是最好的以及为什么?

代码示例1

   while(totalBytesRead < fileSizeFromClient){
            int bytesRemaining = fileSizeFromClient - totalBytesRead;
            int bytesRead = dataInputStream.read(buffer, 0, (int)Math.min(buffer.length, bytesRemaining));

            if(bytesRead == -1){
               break;
             }else{

                dataOutputSream.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;

            }
   }

代码示例2

    while(totalBytesRead < fileSizeFromClient){
          int bytesRemaining = fileSizeFromClient - totalBytesRead;
          int bytesRead = dataInputStream.read(buffer, totalBytesRead, bytesRemaining);

          if(bytesRead == -1){
             break;
             }else{

                dataOutputStream.write(buffer, totalBytesRead, bytesRead);
                totalBytesRead += bytesRead;
            }
   }

1 个答案:

答案 0 :(得分:0)

它们不等同,所以你无法比较它们。第二个示例不能超出某个文件大小和缓冲区大小,因为'totalBytesRead'将溢出缓冲区。它也浪费了大量的空间。除非你需要缓冲区中的文件内容,否则它是一个毫无意义的替代