gpt4 book ai didi

java - AssetFileDescriptor.getFileDescriptor() 有什么用?

转载 作者:行者123 更新时间:2023-11-29 21:29:48 26 4
gpt4 key购买 nike

我在 res/raw 中有一个未压缩的二进制文件,我是这样阅读的:

public byte[] file2Bytes (int rid) {
byte[] buffer = null;
try {
AssetFileDescriptor afd = res.openRawResourceFd(rid);
FileInputStream in = new FileInputStream(afd.getFileDescriptor());
int len = (int)afd.getLength();
buffer = new byte[len];
in.read(buffer, 0, len);
in.close();
} catch (Exception ex) {
Log.w(ACTNAME, "file2Bytes() fail\n"+ex.toString());
return null;
}
return buffer;
}

但是,buffer 没有包含它应该包含的内容。源文件基本上是 1024 个随机字节(二进制 key )。但是 buffer 在写出和检查时是不一样的。在不可打印的字节中,开头出现了 “res/layout/main.xml”(文字路径),然后再往下,是来自 res/raw 的另一个文件的部分文本内容。 O_O?

一段时间后感到恼火,我尝试了:

            AssetFileDescriptor afd = res.openRawResourceFd(rid);
//FileInputStream in = new FileInputStream(afd.getFileDescriptor());
FileInputStream in = afd.createInputStream();

Presto,我得到了正确的内容——这很容易重现。

所以 relevant API docs阅读:

public FileDescriptor getFileDescriptor ()

Returns the FileDescriptor that can be used to read the data in the file.

public FileInputStream createInputStream ()

Create and return a new auto-close input stream for this asset. This will either return a full asset AssetFileDescriptor.AutoCloseInputStream, or an underlying ParcelFileDescriptor.AutoCloseInputStream depending on whether the the object represents a complete file or sub-section of a file. You should only call this once for a particular asset.

为什么从 getFileDescriptor() 构造的 FileInputStream() 最终会产生垃圾,而 createInputStream() 提供正确的访问权限?

最佳答案

根据 pskink 的评论,AssetFileDescriptor() 返回的 FileDescriptor 显然不是 只是 指向文件的 fd —— 它可能指的是 aapt 由资源。

        AssetFileDescriptor afd = res.openRawResourceFd(rid);
FileInputStream in = new FileInputStream(afd.getFileDescriptor());
in.skip(afd.getStartOffset());

原来等同于 FileInputStream in = afd.createInputStream() 版本。

我想在“创建”(新事物)和“获取”(现有事物)之间的区别中有一些暗示。 :/

关于java - AssetFileDescriptor.getFileDescriptor() 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19753021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com