在上一篇 Android 項目中資源文件 -- asset 目錄和 res 目錄 中,我們簡單記錄了一下assets和res目錄下的文件的異同。這篇就簡單介紹一下Android 項目中資源文件 -- assets目錄文件的訪問。

assets簡介

如圖所示,在Android Studio項目中的根目錄下,就會有一個assets的文件目錄(若不存在,可以自己新建)。它里面創(chuàng)建存儲:圖像、音視頻、字體、數(shù)據(jù)庫等等。之所以說它適合用來管理這些文件,是因為程序在編譯時不會去處理這個目錄下的文件,但是會將它們打包進apk中。而其他你隨便創(chuàng)建的目錄在編譯時就會被直接忽略掉。還可以在assets文件中創(chuàng)建子目錄,方便分類管理。
在assets目錄的使用上有一點是要注意的:(這點之前沒有說到過)
assets目錄內的文件在程序打包發(fā)布以后是只讀的。只可讀取不可修改。
assets使用
assets目錄文件的訪問,不同res文件的訪問。Android中提供了一個專門的 android.content.res.AssetManager 類用來對assets文件的訪問。

從上面AssetManager類的結構圖來看,他提供的api方法很多。但是我們需要重點關注的就以下幾個方法:
- 構造方法
- open() 方法
- openFd() 方法
- openNonAssetFd() 方法
- openXmlResourceParser() 方法
構造方法
通常情況下,我們要獲取AssetManager對象的實例時,不需要使用new的方式。通過下面的方式獲?。?/p>
通過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 的形式供使用。
參數(shù)
String fileName指某個文件在assets目錄下的相對路徑。如:aaa.mp3 或者 dir/file.aviint accessMode訪問模式
| 訪問模式 | 說明 |
|---|---|
| ACCESS_UNKNOW | 無模式。其代表的值是 0 |
| ACCESS_RANDOM | 這個不應該翻譯成隨機訪問模式,無序訪問模式會更適合一點。這種模式下文件的訪問只會打開其中一段內容,然后再根據(jù)你的需要向流的前方或后方移動讀取指針。其代表的值是 1 |
| ACCESS_STREAMING | 順序讀取模式。文件將會被從頭部打開,然后按順序向后面移動讀取數(shù)據(jù)。其代表的值是 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();
}