Android项目使用Assets下的文件

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();
		}
	}
}

转载请标明:大飞_Rflyee:http://blog.csdn.net/rflyee/article/details/17341669


发布了57 篇原创文章 · 获赞 86 · 访问量 44万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章