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

Sqlite database not copied from asset folder Android(Sqlite 数据库未从资产文件夹 Android 复制)

本文介绍了Sqlite 数据库未从资产文件夹 Android 复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将名为adinpect"的数据库从资产文件夹复制到应用程序数据库文件夹,但它不起作用...

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

代码(在主要活动 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.

我没有收到任何错误.

有什么建议吗?

谢谢

推荐答案

此代码将帮助您从 assets 文件夹中复制 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 数据库未从资产文件夹 Android 复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Sqlite 数据库未从资产文件夹 Android 复制

基础教程推荐