从ContentResolver的openAssetFileDescriptor方法获取NegativeByteArraySizeException以读取vCardUri。有没有解决方法来解决它?

问题描述 投票:0回答:1

我正在创建一个.VCF文件来备份联系人。创建和插入数据的过程失败,因为FileDescriptor's方法getDeclaredLength返回-1的大小vCard-URI我从ContentResolver's openAssetFileDiscritor方法得到的长度。

这是与asked here by 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-descriptor android-7.0-nougat android-contentresolver
1个回答
0
投票

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

希望这有帮助。干杯

© www.soinside.com 2019 - 2024. All rights reserved.