【问题标题】:getting NegativeByteArraySizeException from ContentResolver's openAssetFileDescriptor method for reading vCardUri. Is there any workaround to fix it?从 ContentResolver 的 openAssetFileDescriptor 方法中获取 NegativeByteArraySizeException 以读取 vCardUri。有什么办法可以解决吗?
【发布时间】:2019-04-27 08:34:09
【问题描述】:

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

这与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】:

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

    希望对您有所帮助。干杯

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 2013-10-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      相关资源
      最近更新 更多