从文件android读取数据时出现ArrayIndexOutOfBoundsException

时间:2014-05-28 13:45:24

标签: android bytearray indexoutofboundsexception bufferedinputstream

我正在使用块中的multipartentity上传视频,上传我正在从文件中读取数据。在第一个循环中,我能够读取数据,但在下一个循环中,它将获得ArrayIndexOutOfBoundsException

例外:

> java.lang.ArrayIndexOutOfBoundsException: length=1024;
> regionStart=1024; regionLength=1024

I am reading 1024 bytes in every loop.

totalSize = 441396

offset starts from 0

chunkSize = 1024

我的代码:

do {
    currentChunkSize = totalSize - offset > chunkSize ? chunkSize : totalSize - offset;

    String urlString = "http://capmem.omsoftware.co/Event/UploadVideo?" +
                            "callback=localJsonpCallback&" +
                            "filename="+ filename +"&" +
                            "ext="+ exten +"&" +
                            "totalsize="+ size +"&" +
                            "EventID="+ eventid +"&" +
                            "UserID="+ userid +"&" +
                            "comment="+ coment +"&" +
                            "VideoLength="+ videolength +
                            "&chunk=" + currentChunkSize;

    httppost1 = new HttpPost(urlString);

    byte[] currentBytes = new byte[currentChunkSize];
    buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(currentBytes, offset, currentChunkSize);

    offset += currentChunkSize;

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("videofile", new ByteArrayBody(currentBytes, "application/octet-stream", filename));

    httppost1.setEntity(reqEntity);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httppost1);
    int resCode = response.getStatusLine().getStatusCode();

} while(totalSize != offset);

中获取例外
buf.read(currentBytes, offset, currentChunkSize);

2 个答案:

答案 0 :(得分:2)

offset参数是您要写入的currentBytes的偏移量,而不是流中的偏移量。由于currentBytes的长度为currentChunkSize,如果offset不是0,你将超过数组的末尾。

答案 1 :(得分:0)

您的currentChunkSize始终为1024,因为您的唯一支票是

currentChunkSize = totalSize - offset > chunkSize ? chunkSize : totalSize - offset;

您永远不会修改totalSize。您需要知道剩下多少字节来确定所需的块大小。

尝试添加

totalSize = totalSize-currentChunkSize; 

您也可以将while条件更改为

while(totalSize!=0)

甚至更好地将其更改为前置条件循环而不是do-while(文件可能为空)