android创建数据库的时候就将数据库保存到sdcard中,将数据库备份到Android上的SDCard...

这段代码展示了如何在Android应用中将内部数据库文件复制到SDCard。首先,获取内部数据库文件路径,然后创建SDCard的目标目录,如果不存在则创建。接着,尝试创建目标文件并使用FileChannel进行文件复制。如果复制成功,显示成功提示;否则,显示失败提示。
摘要由CSDN通过智能技术生成

我正在使用下面的代码将备份副本写入SDCard,我得到了

java.io.IOException: Parent directory of file is not writable: /sdcard/mydbfile.db

private class ExportDatabaseFileTask extends AsyncTask {

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值