我正在尝试/assets
使用以下代码从 Android 文件夹中读取位图:
AssetFileDescriptor fd = getAssets().openFd("pic1.jpg")
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
我得到的异常表明文件权限错误:
java.io.IOException: read failed: EBADF (Bad file number)
at libcore.io.IoBridge.read(IoBridge.java:432)
at java.io.FileInputStream.read(FileInputStream.java:179)
at java.io.BufferedInputStream.fillbuf(BufferedInputStream.java:168)
at java.io.BufferedInputStream.read(BufferedInputStream.java:309)
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
at android.graphics.BitmapFactory.decodeFileDescriptor(BitmapFactory.java:670)
at android.graphics.BitmapFactory.decodeFileDescriptor(BitmapFactory.java:688)
尝试从输入流中读取它会产生类似的异常:
AssetFileDescriptor fd = getAssets().openFd("pic1.jpg");
FileInputStream is = fd.createInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
例外:
java.io.IOException: lseek failed: EBADF (Bad file number)
Stack trace:
at java.io.FileInputStream.skip(FileInputStream.java:197)
at android.content.res.AssetFileDescriptor$AutoCloseInputStream.<init>(AssetFileDescriptor.java:173)
at android.content.res.AssetFileDescriptor.createInputStream(AssetFileDescriptor.java:138)
直接从输入流中读取给出了另一个例外:
InputStream is = getAssets().open("pic1.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(is);
例外:
java.lang.NullPointerException: asset
at android.content.res.AssetManager.seekAsset(Native Method)
at android.content.res.AssetManager.access$600(AssetManager.java:35)
at android.content.res.AssetManager$AssetInputStream.mark(AssetManager.java:567)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:572)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:643)
读取资产的正确方法是什么?