Android將項目中的資料庫複寫到SD

來源:互聯網
上載者:User
將資料庫檔案放到assets下 編寫代碼
/** * 拷貝資料庫 *  * @param ctx * @param isNew */public void copyDatabase(Context ctx, boolean isNew) {// 是否初始化資料庫if(isNew){    // 檢查 SQLite 資料庫檔案是否存在    if ((new File(DB_PATH + DB_NAME)).exists() == false) {        // 如 SQLite 資料庫檔案不存在,再檢查一下 database 目錄是否存在        File f = new File(DB_PATH);        // 如 database 目錄不存在,建立該目錄        if (!f.exists()) {            f.mkdir();        }        try {            // 得到 assets 目錄下我們實現準備好的 SQLite 資料庫作為輸入資料流            InputStream is = ctx.getAssets().open(DB_NAME);            // 輸出資料流            OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);            // 檔案寫入            byte[] buffer = new byte[1024];            int length;            while ((length = is.read(buffer)) > 0) {                os.write(buffer, 0, length);            }            // 關閉檔案流            os.flush();            os.close();            is.close();        } catch (Exception e) {            e.printStackTrace();        }    }}}
兩個重要的變數:
// 資料庫路徑final static String DB_PATH = "/data/data/com.example.test/database/";// 資料庫名稱final static String DB_NAME = "ywyd.sqlite";
測試是否成功:
public void testData(){// 下面測試 /data/data/com.test.db/databases/ 下的資料庫是否能正常工作        SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);        Cursor cursor = database.rawQuery("select * from sys_config", null);        if (cursor.getCount() > 0) {            cursor.moveToFirst();String strtest = cursor.getString(3);// 看輸出的資訊是否正確System.out.println(strtest);        }        cursor.close();}
在Activity中調用:
SqlLiteHelper helper = new SqlLiteHelper();helper.copyDatabase(this.getBaseContext(), true);//helper.testData();
原文地址 http://blog.csdn.net/yueritian/article/details/46471669
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.