Android 项目中资源文件 -- assets目录文件的访问

在上一篇 Android 项目中资源文件 -- asset 目录和 res 目录 中,我们简单记录了一下assets和res目录下的文件的异同。这篇就简单介绍一下Android 项目中资源文件 -- assets目录文件的访问

assets简介

Android项目中的assets目录结构图

如图所示,在Android Studio项目中的根目录下,就会有一个assets的文件目录(若不存在,可以自己新建)。它里面创建存储:图像、音视频、字体、数据库等等。之所以说它适合用来管理这些文件,是因为程序在编译时不会去处理这个目录下的文件,但是会将它们打包进apk中。而其他你随便创建的目录在编译时就会被直接忽略掉。还可以在assets文件中创建子目录,方便分类管理。

在assets目录的使用上有一点是要注意的:(这点之前没有说到过)
assets目录内的文件在程序打包发布以后是只读的。只可读取不可修改。

assets使用

assets目录文件的访问,不同res文件的访问。Android中提供了一个专门的 android.content.res.AssetManager 类用来对assets文件的访问。

AssetManager类结构局部截图

从上面AssetManager类的结构图来看,他提供的api方法很多。但是我们需要重点关注的就以下几个方法:

  • 构造方法
  • open() 方法
  • openFd() 方法
  • openNonAssetFd() 方法
  • openXmlResourceParser() 方法
构造方法

通常情况下,我们要获取AssetManager对象的实例时,不需要使用new的方式。通过下面的方式获取:

  • 通过Context实例的getAssets()方法:mActivity.getAssets();

  • 通过Resource实例的getAssets()方法:mActivity.getResources().getAssets();

open(string) & open(string,int) 方法

open(String fileName) 方法

    /**
     * Open an asset using ACCESS_STREAMING mode.  This provides access to
     * files that have been bundled with an application as assets -- that is,
     * files placed in to the "assets" directory.
     * 
     * @param fileName The name of the asset to open.  This name can be hierarchical.
     * 
     * @see #open(String, int)
     * @see #list
     */
    public @NonNull InputStream open(@NonNull String fileName) throws IOException {
        return open(fileName, ACCESS_STREAMING);
    }

open(@NonNull String fileName, int accessMode) 方法

/**
     * Open an asset using an explicit access mode, returning an InputStream to
     * read its contents.  This provides access to files that have been bundled
     * with an application as assets -- that is, files placed in to the
     * "assets" directory.
     * 
     * @param fileName The name of the asset to open.  This name can be hierarchical.
     * @param accessMode Desired access mode for retrieving the data.
     * 
     * @see #ACCESS_UNKNOWN
     * @see #ACCESS_STREAMING
     * @see #ACCESS_RANDOM
     * @see #ACCESS_BUFFER
     * @see #open(String)
     * @see #list
     */
    public @NonNull InputStream open(@NonNull String fileName, int accessMode) throws IOException {
        Preconditions.checkNotNull(fileName, "fileName");
        synchronized (this) {
            ensureOpenLocked();
            final long asset = nativeOpenAsset(mObject, fileName, accessMode);
            if (asset == 0) {
                throw new FileNotFoundException("Asset file: " + fileName);
            }
            final AssetInputStream assetInputStream = new AssetInputStream(asset);
            incRefsLocked(assetInputStream.hashCode());
            return assetInputStream;
        }
    }

这两个方法的作用是一样的。都是将assets 目录下的某个文件封装成 InputStream 的形式供使用。

参数

  • String fileName 指某个文件在assets目录下的相对路径。如:aaa.mp3 或者 dir/file.avi

  • int accessMode 访问模式

访问模式 说明
ACCESS_UNKNOW 无模式。其代表的值是 0
ACCESS_RANDOM 这个不应该翻译成随机访问模式,无序访问模式会更适合一点。这种模式下文件的访问只会打开其中一段内容,然后再根据你的需要向流的前方或后方移动读取指针。其代表的值是 1
ACCESS_STREAMING 顺序读取模式。文件将会被从头部打开,然后按顺序向后面移动读取数据。其代表的值是 2
ACCESS_BUFFER 缓存读取模式。读取时会将整个文件直接读取到内存中,这种模式适合小文件的读取。其代表的值是 3

在 open(string) 中,它使用的文件读取模式是 ACCESS_STREAMING 模式。

openFd(string) 方法
    /**
     * Open an uncompressed asset by mmapping it and returning an {@link AssetFileDescriptor}.
     * This provides access to files that have been bundled with an application as assets -- that
     * is, files placed in to the "assets" directory.
     *
     * The asset must be uncompressed, or an exception will be thrown.
     *
     * @param fileName The name of the asset to open.  This name can be hierarchical.
     * @return An open AssetFileDescriptor.
     */
    public @NonNull AssetFileDescriptor openFd(@NonNull String fileName) throws IOException {
        Preconditions.checkNotNull(fileName, "fileName");
        synchronized (this) {
            ensureOpenLocked();
            final ParcelFileDescriptor pfd = nativeOpenAssetFd(mObject, fileName, mOffsets);
            if (pfd == null) {
                throw new FileNotFoundException("Asset file: " + fileName);
            }
            return new AssetFileDescriptor(pfd, mOffsets[0], mOffsets[1]);
        }
    }

将 assets 目录中的文件以 FileDescriptor 的形式打开,返回一个 AssetFileDescriptor 实例。

openNonAssetFd(string) & openNonAssetFd(int,string) 方法
    /**
     * Open a non-asset as an asset by mmapping it and returning an {@link AssetFileDescriptor}.
     * This provides direct access to all of the files included in an application
     * package (not only its assets).  Applications should not normally use this.
     *
     * The asset must not be compressed, or an exception will be thrown.
     *
     * @param fileName Name of the asset to retrieve.
     */
    public @NonNull AssetFileDescriptor openNonAssetFd(@NonNull String fileName)
            throws IOException {
        return openNonAssetFd(0, fileName);
    }
    /**
     * Open a non-asset as an asset by mmapping it and returning an {@link AssetFileDescriptor}.
     * This provides direct access to all of the files included in an application
     * package (not only its assets).  Applications should not normally use this.
     *
     * The asset must not be compressed, or an exception will be thrown.
     *
     * @param cookie Identifier of the package to be opened.
     * @param fileName Name of the asset to retrieve.
     */
    public @NonNull AssetFileDescriptor openNonAssetFd(int cookie, @NonNull String fileName)
            throws IOException {
        Preconditions.checkNotNull(fileName, "fileName");
        synchronized (this) {
            ensureOpenLocked();
            final ParcelFileDescriptor pfd =
                    nativeOpenNonAssetFd(mObject, cookie, fileName, mOffsets);
            if (pfd == null) {
                throw new FileNotFoundException("Asset absolute file: " + fileName);
            }
            return new AssetFileDescriptor(pfd, mOffsets[0], mOffsets[1]);
        }
    }

这个方法其实和上面的openFd() 是一样的。只不过它是跳出了 assets 目录的范围限定,是站在工程根目录的视角来打开文件的 FileDescriptor 的。换句话说,它允许打开 APK中任意位置文件的 AssetFileDescriptor 实例。

openXmlResourceParser(int,string) 方法
    /**
     * Retrieve a parser for a compiled XML file.
     * 
     * @param cookie Identifier of the package to be opened.
     * @param fileName The name of the file to retrieve.
     */
    public @NonNull XmlResourceParser openXmlResourceParser(int cookie, @NonNull String fileName)
            throws IOException {
        try (XmlBlock block = openXmlBlockAsset(cookie, fileName)) {
            XmlResourceParser parser = block.newParser();
            // If openXmlBlockAsset doesn't throw, it will always return an XmlBlock object with
            // a valid native pointer, which makes newParser always return non-null. But let's
            // be paranoid.
            if (parser == null) {
                throw new AssertionError("block.newParser() returned a null parser");
            }
            return parser;
        }
    }

打开 assets 目录下的 xml 文件,直接返回 XmlResourceParser 实例。就是官方替我们做了从 InputStream 到 XML 解析器之间的转换。

assets使用举例

最普通的读取 assets 目录的文件

try {
    InputStream is = this.getAssets().open("aaa.png");
    Log.d("type1", "File available:" + is.available());

    InputStream is2 = this.getResources().getAssets().open("bbb.png");
    Log.d("type1", "File available2:" + is2.available());
} catch (IOException e) {
    e.printStackTrace();
}

注意:最后一定不要忘记将用完了的流关闭

读取自定义目录层级的文件的方法。

try {
    InputStream is = this.getAssets().open("a/b/c.png");
    Log.d("type2", "File available:" + is.available());

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

以文件描述符形式读取

//这里将一张图片以 AssetFileDescriptor 的形式读取出来,并转换成 Bitmap 显示在 ImageView 上
try {
    AssetFileDescriptor afd = this.getAssets().openFd("river.png");
    Log.d("type3", "File available:" + afd.getLength());

    InputStream is = afd.createInputStream();
    Bitmap bm = BitmapFactory.decodeStream(is);

    is.close();
    afd.close();

    iv.setImageBitmap(bm);
} catch (IOException e) {
    e.printStackTrace();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355