不从资产文件夹Android复制Sqlite数据库

时间:2012-10-03 17:23:01

标签: android sqlite copy assets

我正在尝试将名为“adinpect”的数据库从资产文件夹复制到应用程序数据库文件夹,但它无法正常工作...

代码(主要活动onCreate(),仅用于测试):

 try {
        String destPath = "/data/data/" + getPackageName() + "/databases";
        File f = new File(destPath);

        if (!f.exists()) {

            f.mkdirs();
            f.createNewFile();
            //---copy the db from the assets folder into the databases folder---
            CopyDB(getBaseContext().getAssets().open("adinspect"), new FileOutputStream(destPath + "/adinspect"));
        }

    } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
    }   catch (IOException e) {
            e.printStackTrace();
    }


 public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {

        //---copy 1K bytes at a time---
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        outputStream.close();

}//end copyDB

创建了“databases”文件夹,但其中没有任何内容,尝试通过DDMS访问它。

我没有收到任何错误。

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:4)

此代码将帮助您从assets文件夹中复制DB。 您可以先检查数据库是否存在。

try{
    // CHECK IS EXISTS OR NOT
    SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/"+getPackageName+"/databases/dbname.sqlite",null, 0);
    dbe.close();
}
catch(Exception e)}
{
    // COPY IF NOT EXISTS
    AssetManager am = getApplicationContext().getAssets();
    OutputStream os = new FileOutputStream("/data/data/"+getPackageName+"/databases/dbname.sqlite");
    byte[] b = new byte[100];
    int r;
    InputStream is = am.open("dbname.sqlite");
    while ((r = is.read(b)) != -1) {
         os.write(b, 0, r);
   }
   is.close();
   os.close();
}
相关问题