gpt4 book ai didi

java - 帮助!使用 ByteArrayInputStream 时出现意外的 java.lang.ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 16:00:54 25 4
gpt4 key购买 nike

使用 ByteArrayInputStream 时出现 java.lang.ArrayIndexOutOfBoundsException。

首先,我使用 ZipInputStream 读取 zip 文件,在循环遍历 zipEntries 时,我使用 ByteArrayInputStream 来捕获每个 zipEntry 的数据使用ZipInputStream.read(byte[] b) 和 ByteArrayInputStream(byte[] b) 方法。

最后,我总共有 6 个不同的 ByteArrayInputStream 对象,其中包含来自 6 个不同 zipEntries 的数据。然后,我使用 OpenCSV 读取每个 ByteArrayInputStream。

读取 6 个 ByteArrayInputStream 对象中的 4 个没有问题,其中字节大小小于 2000。

另外 2 个 ByteArrayInputStream 对象的字节大小分别为 2155 和 4010,CSVreader 只能读取这 2 个对象的部分内容,然后给出 java.lang.ArrayIndexOutOfBoundsException。

这是我用来循环遍历 ZipInputStream 的代码

    InputStream fileStream = attachment.getInputStream();

try {

ZipInputStream zippy = new ZipInputStream(fileStream);
ZipEntry entry = zippy.getNextEntry();

ByteArrayInputStream courseData = null;

while (entry!= null) {

String name = entry.getName();
long size = entry.getSize();

if (name.equals("course.csv")) {
courseData = copyInputStream(zippy, (int)size);
}
//similar IF statements for 5 other ByteArrayInputStream objects
entry = zippy.getNextEntry();
}

CourseDataManager.load(courseData);
}catch(Exception e){
e.printStackTrace();
}

以下是我用来将数据从 ZipInputStream 复制到 ByteArrayInputStream 的代码。

public ByteArrayInputStream copyInputStream(InputStream in, int size)
throws IOException {
byte[] buffer = new byte[size];

in.read(buffer);
ByteArrayInputStream b = new ByteArrayInputStream(buffer);
return b;

}

这 2 组 openCSV 代码能够在抛出异常之前读取几行数据,这让我相信是 byteArray 导致了问题。我能做些什么或解决这个问题吗?我正在尝试创建一个接受 zip 文件的应用程序,同时不在 Web 应用程序中存储任何临时文件,因为我正在部署到 google 应用程序引擎和 tomcat 服务器。

已修复!!!感谢 Stephen C,我意识到 read(byte[]) 并不能读取所有内容,因此我调整了代码以使 copyInputStream 完全发挥作用。

最佳答案

由于这看起来像家庭作业,这里有一个提示:

The read(byte[]) method returns the number bytes read.

关于java - 帮助!使用 ByteArrayInputStream 时出现意外的 java.lang.ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953379/

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