【问题标题】:ArrayIndexOutOfBoundsException while reading data from file android从文件android读取数据时出现ArrayIndexOutOfBoundsException
【发布时间】:2014-05-28 13:45:23
【问题描述】:

我正在使用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);

【问题讨论】:

    标签: android bytearray indexoutofboundsexception bufferedinputstream


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复,但我无法理解您的解释。你能用代码解释一下吗?
    • @user2085965:Gabe 的意思是,您传递给您的read 方法的offset 值指向读取字节被复制到的数组的起始索引; BufferedInputStream 记住并继续从它之前读取的点开始读取。如果您希望您的数组仅包含当前块,则必须将 buf.read(currentBytes, offset, currentChunkSize); 替换为 buf.read(currentBytes, 0, currentChunkSize);
    【解决方案2】:

    您的currentChunkSize 始终是1024,因为您唯一的检查是

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

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

    尝试添加

    totalSize = totalSize-currentChunkSize; 
    

    您也可以将 while 条件更改为

    while(totalSize!=0)
    

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

    【讨论】:

    • 感谢您的回复,同一行代码中出现同样的错误。
    • 好吧,我还注意到您在每次迭代时都打开缓冲区而不在之后关闭它......这也可能导致问题
    猜你喜欢
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2018-04-25
    • 2021-03-28
    • 2019-12-20
    • 2015-05-29
    • 2020-09-01
    相关资源
    最近更新 更多