45
Tôi đang sử dụng mã dưới đây để viết một bản sao lưu để SDCard và tôi nhận đượcLàm một bản sao lưu cơ sở dữ liệu để SDCard trên Android
java.io.IOException: Parent directory of file is not writable: /sdcard/mydbfile.db
private class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(ctx);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
File dbFile =
new File(Environment.getDataDirectory() + "/data/com.mypkg/databases/mydbfile.db");
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("mypck", e.getMessage(), e);
return false;
}
}
// can use UI thread here
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
}
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
}
Bài đăng tuyệt vời, cảm ơn. Tôi xác minh rằng mã này không hoạt động để sao chép cơ sở dữ liệu vào thẻ sd. – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Câu hỏi của bạn là một giải pháp cho tôi. Thanx! ;) –
Đây là thủ thuật tuyệt vời. Nhưng tôi muốn biết rằng làm thế nào để khôi phục lại mà sao lưu .. –