将数据库从资产复制到数据库文件夹

编程入门 行业动态 更新时间:2024-10-19 08:54:05
本文介绍了将数据库从资产复制到数据库文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在主要活动中,我有这个方法将文件从 assets 复制到 databases 文件夹:

In main activity I have this method which copies files from assets to the databases folder:

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

但是一旦用户安装了应用程序,他就会在 LogCat 中收到这个错误:

But once the user installs the app, he gets this error in LogCat:

09-14 22:57:25.694: I/Database(19903): sqlite returned: error code = 14, msg = cannot open file at source line 25467 09-14 22:57:25.694: E/Database(19903): sqlite3_open_v2("/data/data/com.henanet.dalel/databases/mydb.sqlite", &handle, 2, NULL) failed

推荐答案

我的方法

使用以下命令获取您的数据库路径

Get Your Database path using the following

ContextWrapper cw =new ContextWrapper(getApplicationContext()); DB_PATH =cw.getFilesDir().getAbsolutePath()+ "/databases/"; //edited to databases

那你可以往这边走

private void copyDataBase() { Log.i("Database", "New database is being copied to device!"); byte[] buffer = new byte[1024]; OutputStream myOutput = null; int length; // Open your local db as the input stream InputStream myInput = null; try { myInput =myContext.getAssets().open(DB_NAME); // transfer bytes from the inputfile to the // outputfile myOutput =new FileOutputStream(DB_PATH+ DB_NAME); while((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.close(); myOutput.flush(); myInput.close(); Log.i("Database", "New database has been copied to device!"); } catch(IOException e) { e.printStackTrace(); } }

更多推荐

将数据库从资产复制到数据库文件夹

本文发布于:2023-10-26 23:50:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   文件夹   资产

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!