简体   繁体   English

此循环将读取输入流多少次?

[英]How many times will this loop read input stream?

I have a block of uncommented code I'm trying to understand. 我要尝试了解一些未注释的代码。 The comments are my own. 评论是我自己的。

//create an array name header that holds 4 bytes
byte header[] = new byte[4];
int len = 0;
int c = -1;

for(; len != 3; len += c)// run loop till len = 3
{
  try
  {
    //first run of the loop following should be true
    //read 3 bytes and save into header array starting at 0
    // c = number of bytes read (most likely 3 after first run of loop)

    c = is.read(header, len, 3 - len);

  }
  catch(Exception e)
  {
     System.err.println("read header error " + e.getMessage());
     displayErrorMessage(e);
  }
  if(c == -1)
    return null;

}

This code is reading an input stream but I'm not sure how many times it will loop. 这段代码正在读取输入流,但是我不确定它将循环多少次。 I tried running through the loop on paper, replacing len and c each time and after 7 iterations len still did not equal 3. 我尝试在纸上遍历循环,每次都替换lenc并且经过7次迭代len仍然不等于3。

During second run of the loop, len should equal -1 and c should equal 3. The -1 should make the read method throw an IndexOutOfBoundsException because you are trying to save the byte read from the stream to header[-1]. 在循环的第二次运行期间,len应该等于-1,而c应该等于3。-1应该使read方法抛出IndexOutOfBoundsException因为您正试图将从流读取的字节保存到header [-1]。 So since an exception is thrown, the value of c would remain equal to 3 from first run of the loop. 因此,由于引发了异常,因此从循环的第一次运行起,c的值将保持等于3。

Am I right in assuming that since the exception is caught, the for loop does not exit? 我是否可以假设既然捕获了异常,for循环就不会退出?

The number of times the loop will be repeated is not deterministic, since read() might read 3 bytes at the first run, and terminate - or it might read 1 byte at a time, and repeat 3 times. 循环将重复的次数是不确定的,因为read()可能在第一次运行时读取3个字节,然后终止-或者一次读取1个字节,并重复3次。

However, as the comment says - it is very likely that read() will read during the first iteration 3 bytes and the loop will have only one iteration. 但是,正如评论所言read()很可能在第一次迭代中读取3个字节,并且循环中只有一个迭代。
For this case what happen is the following: 对于这种情况,将发生以下情况:

  1. check if len < 3 - it is 检查len < 3
  2. read 3 bytes to the array, and set c = 3 读取3个字节到数组,并设置c = 3
  3. check if c == -1 - it is not 检查c == -1不是
  4. end loop: set len = len + c = 3 结束循环:设置len = len + c = 3
  5. check if len < 3 - it is not: terminate the loop 检查len < 3不是:终止循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM