I am a new Java programmer. When I read source code of Java 17, I want to know how the method of read(byte b[], int off, int len)
works in FileInputStream, FileInputStream's read method . I found it returns readBytes which is a native method, FileInputStream's native readBytes method . I didn't learn C code, so I can't read OpenJDK's source code. When I read Java official documen, I noticed that sentences in FileInputStream read(byte b[], int off, int len)
's description: "See Also:InputStream.read()" ( Java official documentation ). I really found a method in InputStream with the same name and parameters.
So, I want to ask, are these two read methods the same? InputStream's read method
Can I just read InputStream's read(byte b[], int off, int len)
to replace the native read method in FileInputStream?
I didn't learn C code, so I can't read OpenJDK's source code. I try to resolve my question with Java official documentation.
FileInputStream
extends InputStream
and overrides read
in InputStream
. Its difference can be found in the documentation . They are not the same.
To be more specific, in FileInputStream
, its readBytes
calls IO_read
(which finally calls read
function in C) one time to read files.
nread = IO_Read(fd, buf, len);
While in InputStream
, it calls read()
byte by byte.
int c = read();
if (c == -1) {
return -1;
}
b[off] = (byte)c;
int i = 1;
try {
for (; i < len ; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte)c;
}
} catch (IOException ee) {
}
And because of its inheritance, you can call InputStream
's read
using super
keyword.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.