0

这里显示了两个代码示例,说明如何在 inputStream 中读取套接字连接,其中哪个最好,为什么?

代码示例 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;
            }
   }
4

1 回答 1

0

它们不是等效的,因此您无法比较它们。第二个示例在超出特定文件大小和缓冲区大小时不起作用,因为“totalBytesRead”会溢出缓冲区。它还浪费了大量的空间。除非您需要缓冲区中的文件内容,否则这是一个毫无意义的选择

于 2013-09-26T23:40:49.323 回答