gpt4 book ai didi

java - Android 上 SQLite 数据库的简单导出和导入

转载 作者:IT老高 更新时间:2023-10-28 20:34:00 25 4
gpt4 key购买 nike

我正在尝试实现一个简单的 SQLite 导出/导入以进行备份。导出只是存储原始 current.db 文件的副本。我想要导入的只是删除旧的 current.db 文件并将 imported.db 文件重命名为 current.db。这可能吗?当我尝试此解决方案时,我收到以下错误:

06-30 13:33:38.831: ERROR/SQLiteOpenHelper(23570):
android.database.sqlite.SQLiteDatabaseCorruptException: error code 11: database disk image is malformed

如果我在 SQLite 浏览器中查看原始数据库文件,它看起来很好。

最佳答案

我在我的一个应用程序的 SQLiteOpenHelper 中使用此代码来导入数据库文件。

编辑:我将 FileUtils.copyFile() 方法粘贴到问题中。

SQLiteOpenHelper

public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";

/**
* Copies the database file at the specified location over the current
* internal application database.
* */
public boolean importDatabase(String dbPath) throws IOException {

// Close the SQLiteOpenHelper so it will commit the created empty
// database to internal storage.
close();
File newDb = new File(dbPath);
File oldDb = new File(DB_FILEPATH);
if (newDb.exists()) {
FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
getWritableDatabase().close();
return true;
}
return false;
}

FileUtils

public class FileUtils {
/**
* Creates the specified <code>toFile</code> as a byte for byte copy of the
* <code>fromFile</code>. If <code>toFile</code> already exists, then it
* will be replaced with a copy of <code>fromFile</code>. The name and path
* of <code>toFile</code> will be that of <code>toFile</code>.<br/>
* <br/>
* <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
* this function.</i>
*
* @param fromFile
* - FileInputStream for the file to copy from.
* @param toFile
* - FileInputStream for the file to copy to.
*/
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
}

如有必要,不要忘记删除旧的数据库文件。

关于java - Android 上 SQLite 数据库的简单导出和导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6540906/

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