首页 > 解决方案 > 从 ContentResolver 的 openAssetFileDescriptor 方法中获取 NegativeByteArraySizeException 以读取 vCardUri。有什么办法可以解决吗?

问题描述

我正在创建一个用于备份联系人的 .VCF 文件。创建和插入数据的过程失败了,因为该FileDescriptor's方法getDeclaredLength返回了我从该方法获得-1的长度的大小。vCard-URIContentResolver'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);

请给出您的善意建议。谢谢 :)

标签: file-descriptorandroid-7.0-nougatandroid-contentresolver

解决方案


所以我自己想出来了,我会发布答案,以防有人遇到类似问题并坚持解决方案。所以之前的代码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();
}

希望这有帮助。干杯


推荐阅读