4

我正在尝试从外部存储(图片目录)加载 .gif 图像,但我使用以下代码得到“找不到文件异常” 。

    InputStream mInputStream = null;
    AssetManager assetManager = getResources().getAssets();
    try {
        mInputStream = assetManager.open(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath().concat("/01.gif"));          

    } catch (IOException e) {           
        e.printStackTrace();
    }

我也使用手动路径进行了测试,但遇到了同样的异常

mInputStream = assetManager.open("file:///mnt/sdcard/Android/data/com.shurjo.downloader/files/Pictures/01.gif");

清单文件中有 SD 卡的写/读权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

请帮助我如何从外部存储打开文件作为 InputStream。提前致谢。

注意:我在模拟器上测试过,图片文件夹下有一个文件01.gif(请看手册路径)。我可以创建目录并将文件放在这些目录中,但无法通过输入流访问这些文件。

4

1 回答 1

10

AssetManager用于访问应用程序包的assets文件夹中的文件。它不能用于访问外部存储中的文件。

您可以使用以下内容:

final String TAG = "MyAppTag";

File picturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
final int readLimit = 16 * 1024;
if(picturesDir != null){
    imageFile = new File(picturesDir, "01.gif");
} else {
    Log.w(TAG, "DIRECTORY_PICTURES is not available!");
}
if(imageFile != null){
    mInputStream =  new BufferedInputStream(new FileInputStream(imageFile), readLimit);
    mInputStream.mark(readLimit);
} else {
    Log.w(TAG, "GIF image is not available!");
}

另请查看可用的示例代码getExternalFilesDir

更新自:这个

于 2012-05-30T07:26:31.763 回答