user2085965
user2085965

Reputation: 403

ArrayIndexOutOfBoundsException while reading data from file android

I am uploading video using multipartentity in chunks, to upload I am reading data from file. In the first loop I am able to read data, but in the next loop it is getting ArrayIndexOutOfBoundsException

Exception :

> 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

My code:

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);

Getting Exception in

buf.read(currentBytes, offset, currentChunkSize);

Upvotes: 0

Views: 2163

Answers (2)

mihail
mihail

Reputation: 2173

your currentChunkSize is always 1024 since your only check is

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

you never modify the totalSize. You need to know how many bytes are left to determine the chunk size you need.

Try adding

totalSize = totalSize-currentChunkSize; 

also you can change the while condition to

while(totalSize!=0)

and even better to change it to a pre-condition loop instead of the do-while (the file might be empty)

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93698

The offset parameter is the offset into currentBytes you want to write, not the offset into the stream. Since currentBytes is of length currentChunkSize, if offset is anything other than 0 you'll go past the end of the array.

Upvotes: 2

Related Questions