gpt4 book ai didi

java - 输入流读取器

转载 作者:行者123 更新时间:2023-12-02 05:29:09 25 4
gpt4 key购买 nike

我当前正在尝试从服务器读取图像文件,但获取的数据不完整或

Exception in thread "main" 
java.lang.NegativeArraySizeException.

这与缓冲区大小有关吗?我尝试使用静态大小而不是内容长度。请各位指教。

  URL myURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection)myURL.openConnection();
connection.setRequestMethod("GET");
status = connection.getResponseCode();

if (status == 200)
{
int size = connection.getContentLength() + 1024;
byte[] bytes = new byte[size];
InputStream input = new ByteArrayInputStream(bytes);
FileOutputStream out = new FileOutputStream(file);
input = connection.getInputStream();

int data = input.read(bytes);
while(data != -1){
out.write(bytes);
data = input.read(bytes);
}
out.close();
input.close();

最佳答案

让我们检查一下代码:

int size = connection.getContentLength() + 1024;
byte[] bytes = new byte[size];

为什么要在大小上添加 1024 字节?重点是什么?缓冲区大小应该足够大以避免太多读取,但又足够小以避免消耗太多内存。例如,将其设置为 4096。

InputStream input = new ByteArrayInputStream(bytes);
FileOutputStream out = new FileOutputStream(file);
input = connection.getInputStream();

为什么创建一个 ByteArrayInputStream,然后完全忘记它?您不需要 ByteArrayInputStream,因为您不是从字节数组读取,而是从连接的输入流读取。

int data = input.read(bytes);

这会从输入中读取字节。读取的最大字节数是字节数组的长度。返回实际读取的字节数并将其存储在data中。

while (data != -1) {
out.write(bytes);
data = input.read(bytes);
}

因此,您已读取了 data 字节,但并未仅写入数组的前 data 字节。您写入整个字节数组。那是错的。假设您的数组大小为 4096 并且数据为 400,则不是写入已读取的 400 个字节,而是写入 400 个字节 + 数组的剩余 3696 个字节,这可能是 0,也可能具有来自先前的值。读。应该是

out.write(bytes, 0, data);

最后:

out.close();
input.close();

如果之前发生任何异常,这两个流将永远不会关闭。这样做几次,您的整个操作系统将不再有可用的文件描述符。使用try-with-resources声明以确保无论发生什么情况,您的流都会关闭。

关于java - 输入流读取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com