上下文
我正在调整现有项目的一部分以适应gae项目。最初的项目使用FileInputStream和FileOutputStream,但是由于gae不接受FileOutputStream,所以我将用ByteArrayInputStream和ByteArrayOutputStream替换它们。原始代码加载了一些本地文件,我用Datastore Entities替换了这些文件,这些文件在其中一个属性中保存这些文件的内容。
问题
它似乎很有效,但我在这段代码中得到了一个ArrayIndexOutOfBoundsException:
private byte[] loadKey(Entity file) {
byte[] b64encodedKey = null;
ByteArrayInputStream fis = null;
try {
fis = fileToStreamAdapter.objectToInputStreamConverter(file);
b64encodedKey = new byte[(int) fis.available()];
fis.read(b64encodedKey);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return b64encodedKey;
}fileToStreamAdapter.objectToInputStreamConverter(file)接受Datastore Entity并将其属性的内容转换为ByteArrayInputStream。
原始代码:
private byte[] loadKey(String path) {
byte[] b64encodedKey = null;
File fileKey = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(fileKey);
b64encodedKey = new byte[(int) fileKey.length()];
fis.read(b64encodedKey);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return b64encodedKey;
}在FileInputStream和ByteArrayInputStream之间的差异中,是否有什么东西可能导致这个错误?
发布于 2015-03-13 13:37:16
在我看来,如果objectToInputStreamConverter使用ByteArrayInputStream(byte[] buf)创建了ByteArrayInputStream,那么它就可以返回byte[]参数,使您不必再读任何东西,更不用说所有这些错误处理了。
发布于 2015-03-13 13:34:28
fis.available()不是输入流的大小,而是此时缓冲区中可用的数据数量。
如果您需要从输入流返回字节,则必须使用以下内容来复制它:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int l;
byte[] data = new byte[16384];
while ((l = fis.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, l);
}
buffer.flush();
return buffer.toByteArray();或者更好的我们IOUtils从commons-io
https://stackoverflow.com/questions/29033359
复制相似问题