SQLite数据库无法从资源文件夹的Andr​​oid复制文件夹、数据库、资源、SQLite

2023-09-05 03:23:30 作者:孤獨啲亽就應該吃飽飯

我试图复制一个名为从资源文件夹到应用程序的数据库文件夹adinpect数据库,但它不工作...

I am trying to copy a database named "adinpect" from the asset folder to the application databases folder, but it is not working...

code(在主要活动的onCreate(),只是为了测试):

Code (in main activity onCreate(), just for testing):

 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

创建数据库文件夹,但那里什么也没有,试图通过DDMS来访问它。

The "databases" folder is created but there in nothing in it, trying to access it by DDMS.

我没有得到任何错误。

任何建议?

感谢

推荐答案

这code wlll帮你复制数据库从资产的文件夹中。 你可以先检查是否DB存在与否。

This code wlll help you to copy DB from assets folder. You can check first if DB exists or not.

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();
}