1. 程式人生 > >Android中開啟raw目錄下的資料庫檔案

Android中開啟raw目錄下的資料庫檔案



在Android中不能直接開啟res /raw目錄中的資料庫檔案(.db)


想要開啟raw下的db檔案需要如下步驟:


1、在程式第一次啟動時將該檔案複製到手機記憶體或SD卡的某個目錄中。
    複製的基本方法是使用getResources().openRawResource方法獲得res /raw目錄中資源的 InputStream物件,
    然後將該InputStream物件中的資料寫入其他的目錄中相應檔案中。


2、在Android SDK中可以使用SQLiteDatabase.openOrCreateDatabase方法來開啟任意目錄中的SQLite資料庫檔案。


3、使用SQLiteDatabase.qury()可以進行資料查詢


注意:

1、如果將db檔案存入<包名>目錄下,預設會存入databases目錄下

public class MainActivity extends Activity {


    private String f;	//資料庫存入手機的路徑

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //將raw目錄下的db檔案,存入<包名>/databases/目錄下
        writeDB();

        Log.d("Main2Activity", "DB uri : "+ getDatabasePath("a1.db"));

        SQLiteDatabase sqLiteDatabase = openOrCreateDatabase(f, MODE_PRIVATE, null);
        Cursor cursor = sqLiteDatabase.query("student", null, null, null, null, null, null);

        for(int i = 0;cursor.getColumnCount()>0 && i<cursor.getColumnCount();i++){
            if(cursor.moveToNext()){
                int columnIndex = cursor.getColumnIndex("_id");
                String _id = cursor.getString(columnIndex);
                columnIndex = cursor.getColumnIndex("name");
                String name = cursor.getString(columnIndex);

                Log.d("Main2Activity","_id : "+ _id +" , name : "+ name);

            }
        }
    }



    public void writeDB(){
        f = getFilesDir()+"\\databases\\"+"a1.db";  //此處如果是放在應用包名的目錄下,自動放入“databases目錄下
        FileOutputStream fout = null;
        InputStream inputStream = null;
        try {
            inputStream = getResources().openRawResource(R.raw.aaa);
            fout = new FileOutputStream(new File(f));
            byte[] buffer = new byte[128];
            int len = 0;
            while ((len = inputStream.read(buffer))!=-1){
                fout.write(buffer, 0, len);
            }
            buffer = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}