I was running the code below to try and understand how BufferedInputStream works in Java. I set the buffer size to 1 and was expecting the buffer to read the file 465 times because that is how much character is in the file. However, it reads the file once. What I found to change the number of times the buffer reads the file, you change the array of bytes, does, size to 1. In this case it reads the file 465 times. I do not understand why buffer reads the file once even though I set the buffer size 1. How come the array "does" dictates how many times the buffer reads the file?
File f = new File("runs");
if(!f.exists()) {
f.createNewFile();
}
FileInputStream input = new FileInputStream(f);
BufferedInputStream b = new BufferedInputStream(input, 1);
byte[] does = new byte[1000];
int i = b.read(does);
int x = 0;
String tmp;
while(i != -1) {
tmp = new String(does, StandardCharsets.UTF_8);
if(!tmp.equalsIgnoreCase("\n")) {
System.out.print(tmp);
}else {
System.out.println(tmp);
}
x++;
i = b.read(does);
}
System.out.println(x);
}
Let's begin by
InputStream.readwhich reads a single byte of data from the input stream and returns it as anintvalue which will be blocked in 2 condition, the end of the stream is being detected or an exception is thrown. WhileBufferedInputStreamadds buffering to the passed input stream.The difference is
BufferedInputStreamreads data from the underlying input stream in chunks and stores it in an internal buffer so when you callread()method it returns the next byte from its buffer instead so the difference is amount of data call overhead in which theBufferedInputStreamreduce it by grouping multiple requests for data into a fewer calls from the underlying input stream.It will not actually,
BufferedInputStreamdoes not necessarily read the entire file into the buffer even when a buffer size is specified actually it reads data from the file into the buffer in chunks or blocks whose size is at most the size of the buffer,The number of times the file is read depends on the size of the file and the size of the buffer used by, in you shared snippet you specified size of the buffer to 1 and thats the reason you get one byte at a time, which should different, in your case some thing like