zoukankan      html  css  js  c++  java
  • 如何将打开res/raw目录中的数据库文件?

    在Android中不能直接打开res /raw目录中的数据库文件,而需要在程序第一次启动时将该文件复制到手机内存或SD卡的某个目录中,

    然后再打开该数据库文件。

    复制的基本方法是使用getResources().openRawResource方法获得res/raw目录中资源的 InputStream对象,

    然后将该InputStream对象中的数据写入其他的目录中相应文件中。

    在Android SDK中可以使用SQLiteDatabase.openOrCreateDatabase方法来打开任意目录中的SQLite数据库文件。

    实现如下:copyDB();

    private void copyDB() {
    		//只要你拷贝了一次,我就不要你再拷贝了
    		try {
    			File file = new File(getFilesDir(), "address.db");
    			if(file.exists()&&file.length()>0){
    				//正常了,就不需要拷贝了
    				Log.i("copyDB", "正常了,就不需要拷贝了");
    			}else{
    				//().openRawResource
    				//InputStream is = getAssets().open("address.db");
    				InputStream is = getResources().openRawResource(R.raw.address);
    				FileOutputStream fos = new FileOutputStream(file);
    				byte[] buffer = new byte[1024];
    				int len = 0;
    				while((len = is.read(buffer))!= -1){
    					fos.write(buffer, 0, len);
    				}
    				is.close();
    				fos.close();
    			}
    			
    			
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    

    打开数据库:

    	public static String path = "data/data/com.itheima.mobilesafe/files/address.db";
    	
    	public static String SearchNumber(String number){
    		String adrress = number;
    		SQLiteDatabase openDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    		Cursor cursor = openDatabase.rawQuery("select location from data2 where id=(select outkey  from data1 where id=?)", 
    				new String[]{number.substring(0,7)});
    		while(cursor.moveToNext()){
            		String location = cursor.getString(0);
            		 adrress = location ;
    		}
    		return adrress;
    	}
    
  • 相关阅读:
    MoveWindow() SetWindowPos()的区别与联系
    SEO搜索引擎优化基础
    Windows核心编程小结1
    STL学习笔记8 -- 函数对象
    Java关于反射
    多线程处理慢sql查询小笔记~
    前端小菜鸡使用Vue+Element笔记(二)
    前端小菜鸡使用Vue+Element笔记(一)
    Hive/hbase/sqoop的基本使用教程~
    Hive/Hbase/Sqoop的安装教程
  • 原文地址:https://www.cnblogs.com/childhooding/p/4474046.html
Copyright © 2011-2022 走看看