爲什麼你想把數據庫文件直接放入數據/數據文件夾中?爲了測試目的?對我沒有意義,我會選擇以下選項之一:
- 從服務器加載數據並將其插入到數據庫中。
- 將數據庫文件放入資產文件夾,然後複製字節以創建應用程序數據庫(您不能移動數據庫文件)。
實例(如需要):
首先,你需要把你的數據庫文件的資產/數據庫文件夾內。如果你的數據庫大於1MB,你需要分割它。 (即database1,database2,database3 ...)
你可能有一個類來完成所有的數據庫任務,在這裏我有一個名爲DatabaseHelper的類(擴展SQLiteOpenHelper)。不要忘記設置你的數據庫路徑和名稱。
private static String DB_PATH = "/data/data/com.example/databases/";
private static String DB_NAME = "mydb.sqlite";
如果你不得不拆分你的數據庫,也要把這些塊聲明爲一個變量。
private static String[] sFiles = {'database1','database2','database3'};
您可以使用getReadableDatabase()方法快速創建/打開數據庫。
然後,創建一個這樣的實現:
private void copyDatabase() throws IOException {
// Path to the empty database.
String outFilename = DB_PATH + DB_NAME;
// Open the empty database as the output stream.
OutputStream outputDatabase = new FileOutputStream(outFilename);
// Transfer bytes from the input file to the output file.
byte[] buffer = new byte[1024];
for (int i = 0; i < sFiles.length; ++i) {
// Open the local database as the input stream.
InputStream is = mContext.getAssets().open("database/" + sFiles[i]);
int length;
while ((length = is.read(buffer)) > 0) {
outputDatabase.write(buffer, 0, length);
}
// Closing stream.
is.close();
}
// Closing the streams.
outputDatabase.flush();
outputDatabase.close();
// Closing database.
close();
}
你是從哪裏複製的?確切的路徑請。 – st0le 2012-01-02 11:58:45
是位置data/data/your.package.name /數據庫? – 2012-01-02 11:59:26
是數據庫路徑是數據/數據/包/數據庫 – Vamshi 2012-01-02 12:03:01