在assets文件中打开一个图像文件

在assets文件夹中有一个.gif文件。如:assets/Files/android.gif。当打开文件的时候,会在第二行抛出异常:

AssetManager mngr=getAssets();
InputStream is2=mngr.open("Files/android.gif");

那么打开一个文本文件的代码是否适用于打开一个图像文件呢?

打开图像文件:

InputStream bitmap=null;

try {
    bitmap=getAssets().open("icon.png");
    Bitmap bit=BitmapFactory.decodeStream(bitmap);
    img.setImageBitmap(bit);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    bitmap.close();
}

我刚刚试了一下,没有问题的。

    public void testShow()
{
    InputStream in = null;
    FileOutputStream fos = null;
    try
    {
        in = getAssets().open("Files/test.png");
        File f = new File("/sdcard/uery.png");
        if (!f.exists())
        {
            f.createNewFile();
        }
        fos = new FileOutputStream(f);
        byte[] buffer = new byte[1024];
        int count = 0;
        while ((count = in.read(buffer)) > 0)
        {
            fos.write(buffer);
            fos.flush();
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (fos != null)
        {
            try
            {
                fos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if (in != null)
        {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

不知道是不是图片格式有问题哦...

我猜想你是不是收到提醒有未处理的IOException型异常。如果那样的话,要添加:

AssetManager mngr = getAssets();
try {
    InputStream is2 = mngr.open("Files/android.gif");
} catch (final IOException e) {
    e.printStackTrace();
}