SQLite数据库无法从资源文件夹的Andr​​oid复制 [英] Sqlite database not copied from asset folder Android

查看:146
本文介绍了SQLite数据库无法从资源文件夹的Andr​​oid复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图复制一个名为从资源文件夹到应用程序的数据库文件夹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();
}

这篇关于SQLite数据库无法从资源文件夹的Andr​​oid复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆