gpt4 book ai didi

java - 写入文件时出现 IndexOutOfBoundException

转载 作者:行者123 更新时间:2023-12-01 23:29:38 26 4
gpt4 key购买 nike

我使用此代码写入文件,它抛出 IndexOutOfBoundException

InputStream is = res.openStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] array = new byte[1024];
for(int i = is.read(array); i != 1; i=is.read(array)) {
fos.write(array, 0, i);
}

如何检查还剩多少字节要写入?

最佳答案

当没有任何内容可读取时,read 方法返回 -1 而不是 1。因此,循环中的检查必须是:

for(int i = is.read(array); i != -1; i=is.read(array))

关于java - 写入文件时出现 IndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19538018/

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