我正在尝试使用以下代码从Android /assets
文件夹中读取位图:
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)
阅读资产的正确方法是什么?
答案 0 :(得分:6)
问题是我没有从主线程中读取资产。在我正在开发的应用程序中,两个列表项可以同时加载相同的,相当大的资产。
简而言之,如果在另一个线程试图访问该文件时仍然正在读取该文件,则会抛出IOException
并显示“lseek failed:EBADF(Bad file number)”。