从URL下载文件时,为什么要读入字节数组?
When downloading a file from a URL, why do we read into a byte array?
为什么从 URL 下载文件时要读入字节数组?在下面的代码中,创建了一个字节数组 ('data'),它分配了一个数字“1024”,并在下面的代码中作为参数传递
while ((x = in.read(data, 0, 1024)) >= 0)
能否请您解释一下 "reading" 到字节数组的含义?另外,为什么还要传入“0”和“1024”?
此代码取自 Java getting download progress
URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
"package.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
Can you please explain what "reading" into a byte array means?
当我们将数据读入一个字节数组时,我们的意思是我们将来自输入流的数据存储到一个数组中以备后用。我们将数据读入字节数组而不是 char 数组或 int 数组,因为它是二进制数据。它可能是文本或图片或视频。归根结底,这些都是我们以字节为单位存储的二进制数据。
Also, why were "0" and "1024" passed in as well?
The documentation for read()
表示需要 3 个参数:
b - destination buffer.
off - offset at which to start storing bytes.
len - maximum number of bytes to read.
所以 0
是读取操作开始存储字节的“偏移量”。 1024
是要读取的字节数。这些可以是任何合理的数字,只要您不尝试读入超出数组末尾的位置即可。
为什么从 URL 下载文件时要读入字节数组?在下面的代码中,创建了一个字节数组 ('data'),它分配了一个数字“1024”,并在下面的代码中作为参数传递
while ((x = in.read(data, 0, 1024)) >= 0)
能否请您解释一下 "reading" 到字节数组的含义?另外,为什么还要传入“0”和“1024”?
此代码取自 Java getting download progress
URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
"package.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
Can you please explain what "reading" into a byte array means?
当我们将数据读入一个字节数组时,我们的意思是我们将来自输入流的数据存储到一个数组中以备后用。我们将数据读入字节数组而不是 char 数组或 int 数组,因为它是二进制数据。它可能是文本或图片或视频。归根结底,这些都是我们以字节为单位存储的二进制数据。
Also, why were "0" and "1024" passed in as well?
The documentation for read()
表示需要 3 个参数:
b - destination buffer.
off - offset at which to start storing bytes.
len - maximum number of bytes to read.
所以 0
是读取操作开始存储字节的“偏移量”。 1024
是要读取的字节数。这些可以是任何合理的数字,只要您不尝试读入超出数组末尾的位置即可。