gpt4 book ai didi

android - 复制数据库文件到本地存储

转载 作者:行者123 更新时间:2023-11-29 02:21:34 32 4
gpt4 key购买 nike

我在 assete 文件夹中有一个 sqlite 数据库。

我想将其复制到本地存储。

我使用这段代码,它复制没有表的数据库。当我想在 sqlliteeditor 中打开数据库时,出现错误 14。

  private void copyDataBase2() throws IOException {
OutputStream os = new FileOutputStream( "/data/data/pakagename/Learning.db");
InputStream is = context.getAssets().open("databases/Learning.db");
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.flush();
os.close();
}

最佳答案

尝试像这样复制数据库文件:

public class DbHelper extends SQLiteOpenHelper {
private static String DB_PATH = new File(getFilesDir(), "databases").getPath();
private static String DB_NAME = "test_db.db";
private SQLiteDatabase dataBase;
private final Context fContext;
public DbHelper(Context context) {
super(context, DB_NAME, null, 1);
this.fContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
//ничего не делаем – файл базы данных уже есть
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
//файл базы данных отсутствует
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream input = fContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream output = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
}
public void openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
dataBase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (dataBase != null)
dataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

如果您使用 API 19 或更高版本:

String db_path = fContext.getDatabasePath(DB_NAME);

When i want to open database in sqlliteeditor, i get error 14.

此外,我建议您检查数据库文件。如果在编辑器中打开时出现错误,很可能不是文件复制算法的问题。

关于android - 复制数据库文件到本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55293020/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com