我有一个应用程序,可以创建和更新自己的MySQL数据库。我现在想要允许用户导出数据库的副本(用于备份),然后再导入该文件。在此过程中,我无需更改数据库的格式。
我不确定最好/最简单的方法。我已经能够使用下面的代码将我的应用程序导出数据库到SD卡,但问题是 - 如何让我的应用程序再次导入此文件?
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
Toast.makeText(getBaseContext(), sd.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), data.toString(), Toast.LENGTH_LONG).show();
if (sd.canWrite()) {
String currentDBPath = "//data//"+ packageName +"//databases//"+ class_dbname; //dbList[0];
String backupDBPath = "//data//"+ class_dbname; //dbList[0];
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
答案 0 :(得分:1)
我是这样做的:
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.
DBHelper.getWritableDatabase().close();
return true;
}
return false;
}
“copyFile()”方法是:
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();
}
}
}
}
此致