Android项目在编译时,Assets下文件不被编译。
Assets下的文件除了 html文件可以直接在项目中使用外,
其他的文件都需要做处理。
在项目中使用方法:
使用流读取。
AssetManager manager = getAssets();
InputStream open = manager.open("logo.png");
注意:某些经常使用的文件(比如数据库a.db),可以在项目初始化时将其copy到手机中存储。示例见下边2
示例一
Get the AssetManager
AssetManager manager = getAssets();
// read a Bitmap from Assets
InputStream open = null;
try {
open = manager.open("logo.png");
Bitmap bitmap = BitmapFactory.decodeStream(open);
// Assign the bitmap to an ImageView in this layout
ImageView view = (ImageView) findViewById(R.id.imageView1);
view.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (open != null) {
try {
open.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实例二
/**
* 拷贝assets中的电话归属地数据库文件
*/
private void copyAddrDB() {
File file = new File(getFilesDir(), "address.db");
if (file.exists()) {
Log.i("log:SplashActivity", "数据库已经存在,不需要拷贝");
} else {
Log.i("log:SplashActivity", "开始拷贝了。。。。");
// 拷贝
try {
InputStream is = getAssets().open("address.db");
// 获取数据库库文件输入流
FileOutputStream fos = new FileOutputStream(file);
// 定义输出流
byte[] bt = new byte[8192];
int len = -1;
while((len = is.read(bt)) != -1){
fos.write(bt, 0, len);
}
is.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
网友评论