android匯入外部已存在的資料庫大於1M的資料庫檔案方法

來源:互聯網
上載者:User
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;/** * 將把assets下的資料庫檔案直接複製到DB_PATH,但資料庫檔案大小限制在1M以下 * 如果有超過1M的大檔案,則需要先分割為N個小檔案,然後使用copyBigDatabase()替換copyDatabase() */public class DBManager extends SQLiteOpenHelper {    // 使用者資料庫檔案的版本    private static final int DB_VERSION = 1;    // 資料庫檔案目標存放路徑為系統預設位置,com.rys.lb 是你的包名    private static String DB_PATH = "/data/data/com.chishacai/";    // 如果你想把資料庫檔案存放在SD卡的話    // private static String DB_PATH =    // android.os.Environment.getExternalStorageDirectory().getAbsolutePath()    // + "/arthurcn/drivertest/packfiles/";    private static String DB_NAME = "cscpb.db";    private static String ASSETS_NAME = "cscdb/cscpb.db";    private SQLiteDatabase myDataBase;    private final Context myContext;    /**     * 如果資料庫檔案較大,使用FileSplit分割為小於1M的小檔案 此例中分割為 data.db.100 data.db.101     * data.db.102....     */    // 第一個檔案名稱尾碼    private static final int ASSETS_SUFFIX_BEGIN = 0;    // 最後一個檔案名稱尾碼    private static final int ASSETS_SUFFIX_END = 3;        private static SQLiteDatabase credb ;    /**     * 在SQLiteOpenHelper的子類當中,必須有該建構函式     * @param context 內容物件     * @param name 資料庫名稱     * @param factory 一般都是null     * @param version 當前資料庫的版本,值必須是整數並且是遞增的狀態     */    public DBManager(Context context, String name, CursorFactory factory,            int version) {        // 必須通過super調用父類當中的建構函式        super(context, name, null, version);        this.myContext = context;    }    public DBManager(Context context, String name, int version) {        this(context, name, null, version);    }    public DBManager(Context context, String name) {        this(context, name, DB_VERSION);    }    public DBManager(Context context) {        this(context, DB_PATH + DB_NAME);    }    public void createDataBase() throws IOException {        boolean dbExist = checkDataBase();        if (dbExist) {            // 資料庫已存在,do nothing.            System.out.println("資料庫已經存在");        } else {            // 建立資料庫            try {                File dir = new File(DB_PATH);                if (!dir.exists()) {                    dir.mkdirs();                }                File dbf = new File(DB_PATH + DB_NAME);                if (dbf.exists()) {                    dbf.delete();                }                credb = SQLiteDatabase.openOrCreateDatabase(dbf, null);                // 複製asseets中的db檔案到DB_PATH下                // copyDataBase();                copyBigDataBase();            } catch (IOException e) {                throw new Error("資料庫建立失敗");            }        }    }    // 檢查資料庫是否有效    private boolean checkDataBase() {        SQLiteDatabase checkDB = null;        String myPath = DB_PATH + DB_NAME;        try {            checkDB = SQLiteDatabase.openDatabase(myPath, null,                    SQLiteDatabase.OPEN_READONLY);        } catch (SQLiteException e) {            // database does't exist yet.        }        if (checkDB != null) {            checkDB.close();            System.out.println("關閉");        }        return checkDB != null ? true : false;    }    public DBManager open1() {        String myPath = DB_PATH + DB_NAME;        System.out.println("資料庫已經...");        myDataBase = SQLiteDatabase.openDatabase(myPath, null,                SQLiteDatabase.OPEN_READONLY);        System.out.println("資料庫開啟");        return this;    }    /**     * Copies your database from your local assets-folder to the just created     * empty database in the system folder, from where it can be accessed and     * handled. This is done by transfering bytestream.     * */    private void copyDataBase() throws IOException {        // Open your local db as the input stream        InputStream myInput = myContext.getAssets().open(ASSETS_NAME);        // Path to the just created empty db        String outFileName = DB_PATH + DB_NAME;        // Open the empty db as the output stream        OutputStream myOutput = new FileOutputStream(outFileName);        // transfer bytes from the inputfile to the outputfile        byte[] buffer = new byte[1024];        int length;        while ((length = myInput.read(buffer)) > 0) {            myOutput.write(buffer, 0, length);        }        // Close the streams        myOutput.flush();        myOutput.close();        myInput.close();    }    // 複製assets下的大資料庫檔案時用這個    private void copyBigDataBase() throws IOException {        InputStream myInput;        String outFileName = DB_PATH + DB_NAME;        OutputStream myOutput = new FileOutputStream(outFileName);        for (int i = ASSETS_SUFFIX_BEGIN; i < ASSETS_SUFFIX_END + 1; i++) {            myInput = myContext.getAssets().open(ASSETS_NAME + "." + i);            byte[] buffer = new byte[1024];            int length;            while ((length = myInput.read(buffer)) > 0) {                myOutput.write(buffer, 0, length);            }            myOutput.flush();            myInput.close();        }        myOutput.close();        System.out.println("資料庫已經複製");    }        /**     * 關閉剛建立的資料庫     */    public void closedb() {        if(credb != null) {            credb.close() ;            System.out.println("建立的資料庫已關閉");        }    }    @Override    public synchronized void close() {        if (myDataBase != null) {            myDataBase.close();            System.out.println("關閉成功1");        }        super.close();        System.out.println("關閉成功2");    }    /**     * 該函數是在第一次建立的時候執行, 實際上是第一次得到SQLiteDatabase對象的時候才會調用這個方法     */    @Override    public void onCreate(SQLiteDatabase db) {    }    /**     * 資料庫表結構有變化時採用     */    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    }    public void open() {        SQLiteDatabase DataBase = this.openOrCreateDatabase("data.db",        null);    }    private SQLiteDatabase openOrCreateDatabase(String string, Object object) {        // TODO Auto-generated method stub        return null;    }}

 

改了一點點東西,代碼的注釋就能看懂。

1.如果資料庫檔案大於1M,就用Filesplit工具切割。先去下載這個軟體工具2.首先把已有的資料庫放到assets檔案夾下面,如果沒有這個檔案就先在android項目中建立這個檔案夾。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.