我正在尝试从外部存储(图片目录)加载 .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");
menifest文件中有SD卡的读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
请帮助我如何从外部存储打开文件作为 InputStream。提前致谢。
注意:我已经在模拟器上测试过了,Pictures文件夹下有一个01.gif文件(请看手册路径)。我可以创建目录并将文件放入这些目录,但无法通过输入流访问这些文件。
最佳答案
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
中提供的示例代码
更新自: this
关于java - 如何从 Android 上的外部存储打开 .gif 文件作为 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811730/