如何从android上的外部存储打开.gif文件作为InputStream [英] How to open .gif file as InputStream from external storage on android

查看:38
本文介绍了如何从android上的外部存储打开.gif文件作为InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to load .gif image from external storage (pictures directory) but I am getting 'file not found exception' using the following code.

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

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

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

I have also tested using manually path but got same exception

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

menifest 文件中有对 SD 卡的写/读权限

There is a write/read permission from the SD card in menifest file

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

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

Please help me how can I open a file as InputStream from external storage. Thanks in advance.

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

Note: I have tested it on emulator and there is a file 01.gif under Pictures folder (please see manual path). I can create directories and put files in those directories but can not able to access those files though Input Stream.

推荐答案

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

AssetManager is for accessing the files in the assets folder of the application package. It cannot be used to access files in the external storage.

您可以使用以下内容:

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

更新自:

这篇关于如何从android上的外部存储打开.gif文件作为InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆