How to wrap Uri content with a nio.ByteBuffer on Android?

342 views Asked by At

I'm trying to read content from a Uri on Android, and I need the final Object type passed to the underlying SDK to by a nio.ByteBuffer.

I can get my hands on an InputStream, via ContentResolver but didn't find a way to wrap it with an nio.ByteBuffer.

Is there a way to convert a Uri content to a nio.ByteBuffer on Android?

2

There are 2 answers

0
TacB0sS On BEST ANSWER

I've ended up downloading the content of the Uri locally and open it via other method to get the ByteBuffer

0
jackycflau On

Suppose you are working on an Activity,

private ByteBuffer getByteBuffer(Uri uri){
    try{
        InputStream iStream = getContentResolver().openInputStream(uri);
        if(iStream!=null){
            //value of MAX_SIZE is up to your requirement
            final int MAX_SIZE = 5000000;
            byte[] byteArr = new byte[MAX_SIZE];
            int arrSize = 0;
            while(true){
                int value = iStream.read(byteArr);
                if(value == -1){
                    break;
                }else{
                    arrSize += value;
                }
            }
            iStream.close();
            return ByteBuffer.wrap(byteArr, 0, arrSize);
        }
    }catch(IOException e){
        //do something
    }
    return null;
}

Notes:

(i) InputStream.read(byte[] b) will return an Integer which indicate total number of bytes read into the byte array b at each time.

(ii) If InputStream.read(Byte[] b) returns -1, it indicates that it is the end of the inputStream.

(iii) arrSize stores the total number of bytes read, i.e. the length of byte[] b

(iv) ByteBuffer.wrap(byte[] b, int offset, int length) will wrap the byte array to give a ByteBuffer. You may check this reference

(v) ContentResolver.openInputStream(Uri uri) and InputStream.read(byte[] b) will throw IOException so you must handle it.

(vi) Caution: IndexOutOfBoundException might happen if arrSize > MAX_SIZE, you may need to add if-else clause to handle such issue.

Please feel free to comment or change the code if there is any mistake or if there is a faster way to do that. Happy coding