流式传输时缓冲区字节数组如何连续填充? [英] How the buffer byte array is continuously filling while streaming?

查看:160
本文介绍了流式传输时缓冲区字节数组如何连续填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码用于阅读文件

 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();

根据 read()方法的api


将此输入流中的b.length个字节数据读入一个字节数组。此方法会阻塞,直到某些输入可用。

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    }

readBytes 的源代码是

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

有人提到如何 bytes 。 。

我上传了一个500MB的文件没有任何问题,分配 1000 bytes array

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

推荐答案

如果你问为什么你可以用大约1 KB的缓冲区读取一个~500 MB的文件,那是因为你覆盖了每次循环时缓冲区的内容(大约500,000次)。

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).

如果你问的是如何实际实现read函数,请注意底层call包含关键字 native 。这意味着通过JNI调用本机代码。确切的实现将取决于JVM和OS。

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.

这篇关于流式传输时缓冲区字节数组如何连续填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆