您的位置:首页 > 移动开发 > Android开发

Android读取assets目录下文件

2015-12-15 11:15 501 查看
assets类资源放在工程根目录的assets目录下,它里面保存的是一些原始的文件,可以以任何方式来进行组织,这些文件最终会被原装不动地打包在apk文件中。

要在程序中访问这些文件,根据访问需求,可以分为四种情况:1.访问assets文件夹下已知命名的单个文件;2.访问assets文件夹下所有文件;3.访问assets子文件夹下已知命名的单个文件;4.访问assets子文件下所有文件。

1.访问assets文件夹下已知命名的单个文件

假设在assets目录下有一个名称为filename的文件,那么就可以使用以下代码来访问它:

private AssetManager assets = null;

try {
assets = getContext().getAssets();
InputStream is = assets.open("filename");
} catch (IOException e) {
e.printStackTrace();
}


2.访问assets文件夹下所有文件

private String[] images = null;

try {
assets = getContext().getAssets();
images = assets.list("");
} catch (IOException e) {
e.printStackTrace();
}


其中images字符串数组为assets目录下所有文件文件名(包含后缀),获取所有文件名后,根据文件名获取文件:

InputStream assetFile = null;
try {
// 打开指定资源对应的输入流
assetFile = assets.open(images[position]);
} catch (IOException e) {
e.printStackTrace();
}
BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
// 如果图片还未回收,先强制回收该图片
if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()) {
bitmapDrawable.getBitmap().recycle();
}
// 改变ImageView显示的图片
Bitmap bitmap = BitmapFactory.decodeStream(assetFile);
imageView.setImageBitmap(bitmap);


注意:本例中assets文件夹下所有文件均为.png文件,但获取的文件名中却包含一些其他的未知文件名:





为正常显示,必须过滤掉这些未知的文件,此处我过滤掉了后缀不为.png的文件名:

String names = "";
for (int i = 0; i < images.length; i++) {
if (images[i].endsWith(".png")) {
names += images[i] + ";";
}
}
images = null;
images = names.split(";");


3.访问assets子文件夹下已知命名的单个文件

假设在assets文件夹下存在子文件夹abc,abc文件夹中存在名为filename的文件:

InputStream assetFile = null;
try {
// 打开指定资源对应的输入流
assetFile = assets.open("abc/" + filename);
} catch (IOException e) {
e.printStackTrace();
}


4.访问assets子文件夹中所有文件

同上,获取assets子文件夹abc中所有文件文件名:

try {
assets = getContext().getAssets();
images = assets.list("abc");
} catch (IOException e) {
e.printStackTrace();
}


然后根据文件名逐一读取文件:

InputStream assetFile = null;
try {
// 打开指定资源对应的输入流
assetFile = assets.open("abc/" + images[position]);
} catch (IOException e) {
e.printStackTrace();
}


经测试,子文件夹中不存在上面提到的未知文件,但未知文件到底为什么会产生,何时产生,还需要进一步学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: