如何用nio包装Uri内容。Android上的ByteBuffer?
-
21-12-2019 - |
题
我试图从Android上的Uri读取内容,并且我需要nio传递给底层SDK的最终对象类型。字节缓冲。
我可以通过ContentResolver获得一个InputStream,但没有找到用nio包装它的方法。字节缓冲。
有没有办法将Uri内容转换为nio。Android上的ByteBuffer?
解决方案
我已经结束了本地下载URI的内容,并通过其他方法打开它来获取ByteBuffer
其他提示
假设你正在做一个活动,
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;
}
注意事项:
(一) InputStream.read(byte[] b)
将返回一个整数,该整数指示读入字节数组的总字节数 b
在每一个时间。
(ii)如果 InputStream.read(Byte[] b)
返回-1,表示是inputStream的结尾。
(三) arrSize
存储读取的总字节数,即的长度 byte[] b
(四) ByteBuffer.wrap(byte[] b, int offset, int length)
将包装字节数组以给出一个ByteBuffer。你可以检查一下 参考资料
(五) ContentResolver.openInputStream(Uri uri)
和 InputStream.read(byte[] b)
会抛出IOException,所以你必须处理它。
(vi)谨慎: IndexOutOfBoundException
如果 arrSize
> MAX_SIZE
, ,您可能需要添加if-else子句来处理此类问题。
如果有任何错误或者有更快的方法,请随时评论或更改代码。快乐编码
不隶属于 StackOverflow