In: Computer Science
Consider the following code used to read a file.
byte[] buffer = new byte[BUFFER_SIZE]; String str = ""; try { while (true) { int read = infile.read(buffer); if (read <= 0) { break; } str += new String(buffer, 0, read); } } catch (IOException ex) { return; }
Consider if BUFFER_SIZE is set to 1000 and the the file is 2775 bytes long.
How many times will infile.read() be called? | |
What value will infile.read() return on the next to last time it is called? | |
What value will infile.read() return on the last time it is called? |
In the above program. Buffer is an array of type Byte with 1000 elements in it. infile.read() returns the total number of bytes read from the file since the file is 2775 Bytes long ,when we read using buffer Bytes array we will get 1000 bytes in first iteration, another 1000 in next iteration , 775 in second last iteration , and 0 in the final iteration 1) Hence the inFile.read() function will be called a total 4 times 2) The infile.read() will return 775 in the next to last time 3) The infile.read() will return 0 when it is called the last time byte[] buffer = new byte[BUFFER_SIZE]; String str = ""; try { while (true) { int read = infile.read(buffer); if (read <= 0) { break; } str += new String(buffer, 0, read); } } catch (IOException ex) { return; }