Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

java - How the buffer byte array is continuously filling while streaming?

The below piece of code using to reading for Files

 int bytesRead;
 byte[] bytes = new byte[1000];  //buffer
 FileInputStream fis = new FileInputStream(uploadedFile);

    while ((bytesRead = fis.read(bytes)) != -1) {
          fis.read(bytes, 0, bytesRead);
    }

fis.close();

As per api of read() method

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

There is no where specified that it refills the bytes array,but the stream filling the array until the file successfully read..

But how the internally it's maintaining to get this magic done ??

I saw source code or read method

public int More ...read(byte b[]) throws IOException {
214        return readBytes(b, 0, b.length);
215    }

and readBytes's source code is

200    private native int More ...readBytes
                (byte b[], int off, int len) throws IOException;

There is noting mentioned that how bytes ..

I uploaded a 500MB file without any problem,with allocation that 1000 bytes array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're asking why you can read a ~500 MB file with a roughly 1 KB buffer, it's because you overwrite the contents of the buffer each time you go through the loop (approximately 500,000 times).

If you're asking how the read function is actually implemented, notice that the underlying call includes the keyword native. That means that native code is being called via JNI. The exact implementation is going to be JVM and OS dependent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...