- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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/
我在 res/raw 中有一个未压缩的二进制文件,我是这样阅读的: public byte[] file2Bytes (int rid) { byte[] buffer = null;
现在我正在使用 AssetFileDescriptor 开发音频播放器。但是这首歌(R.raw.music3)不会正常播放,我找不到我做错了什么,请帮我解决这个问题。 private void pla
Android API 中的 AssetFileDescriptor 确实有一个 close method .但是,文档指出这只是一种方便的方法。 AssetFileDescriptor 对象在使用后
我正在尝试使用以下代码从 Android /assets 文件夹中读取位图: AssetFileDescriptor fd = getAssets().openFd("pic1.jpg") Bitma
出于基准测试目的,我重复从 Assets 加载数据并使用 Superpowered SDK 处理它。为了使用 Superpowered SDK 打开 Assets ,我在 Java 端创建了一个 As
在 Android 7 中,getContentResolver().openAssetFileDescriptor(vCardUri, "r")返回 AssetFileDescriptor getD
我是一名优秀的程序员,十分优秀!