file-descriptor - 从 ContentResolver 的 openAssetFileDescriptor 方法中获取 NegativeByteArraySizeException 以读取 vCardUri。有什么办法可以解决吗?
问题描述
我正在创建一个用于备份联系人的 .VCF 文件。创建和插入数据的过程失败了,因为该FileDescriptor's
方法getDeclaredLength
返回了我从该方法获得-1
的长度的大小。vCard-URI
ContentResolver's
openAssetFileDiscritor
这与Balakrishna Avulapati 在这里提出的问题完全相同。但是在这里提出相同问题的唯一问题是,所提出的解决方案对我来说有点难以理解。这不能解决我的问题。@pskink在上述链接的解决方案中的评论可能很有用,但我能够找到完整的源代码,因为评论中只提供了 1 行。
我正在使用以下代码,
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] b = new byte[(int)fd.getDeclaredLength()];
fis.read(b);
请给出您的善意建议。谢谢 :)
解决方案
所以我自己想出来了,我会发布答案,以防有人遇到类似问题并坚持解决方案。所以之前的代码byte[] b = new byte[(int)fd.getDeclaredLength()];
是一样的。将此行更改为byte[] buf = readBytes(fis);
,方法readBytes(FileInputStream fis)
如下。
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
希望这有帮助。干杯
推荐阅读
- r - 在计算 P^n 时,matrixpower() 和 markov() 有什么区别?
- javascript - 如何在自动输入javascript时更改textarea中的文本
- angular - Okta 登录小部件打破了 Jest 测试 - TypeError:无法读取 null 的属性“backingStorePixelRatio”
- go - 工作池实施上的退出通道
- internet-explorer-11 - 在 IE11 中禁用 HTTP2
- ruby - 如何使用 HTTParty 对 GitHub 进行身份验证以抓取页面?
- rabbitmq - 使用 MassTransit 时,发布者确认是否默认处于活动状态?
- python - 仅在拖动游戏窗口时才绘制对象
- flutter - Flutter 小部件测试:如果小部件有键,则 find.byKey 不起作用: GlobalKey(debugLabel: "gridView")
- c# - 无法在字符串中获取正则表达式匹配的值