我正在读取一个大的zip文件,但我的代码给了我负数组大小异常
// Simplest read of an entire file into a byte array
// Will throw exceptions for file not found etc.
private static byte[] loadFileAsByteArray(String path) throws IOException {
File file = new File(path);
InputStream is = new FileInputStream(file);
byte[] data = new byte[(int) file. Length()];
is.read(data);
return data;
}
请告诉我如何读取以字节为单位的长zip文件数据
您的代码至少有一个错误:file. Length()
没有提供您想要的结果
(实际上可能根本不会编译(
假设您想要的是file.length()
对于您的问题:
只有当您正在读取的文件长度超过2147483647字节时,您才能获得负数组大小
在这种情况下,强制转换为int会产生一个负值
此外:即使您的数组足够大,可以包含所有数据,也不能保证is.read(data);
会一次性读取所有数据。你需要一个循环
最后:记住使用try-with-resources关闭InputStream&使最终变量成为最终变量
这个怎么样?:
private static byte[] loadFileAsByteArray(final String path) throws IOException {
final File file = new File(path);
try (final InputStream is = new FileInputStream(file)) {
final byte[] data = new byte[(int) file.length()]; // Cast -> -ve Array-Size?
int off = 0;
int len;
while (-1 != (len = is.read(data, off, data.length - off))) {
off += len;
}
return data;
}
}