无法将sqlite DB导出到SD卡

时间:2012-10-01 04:22:00

标签: android database sqlite

我一直在尝试使用

将我的数据库文件导出到我的Android手机的外部存储器中
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";

 //Get a reference to the database
    File dbFile = this.getDatabasePath(DB_NAME);
    //Get a reference to the directory location for the backup
    File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
    if (!exportDir.exists()) {
      exportDir.mkdirs();
    }
    File backup = new File(exportDir, dbFile.getName());
    //Check the required operation String command = params[0];

    //Attempt file copy
    try {
      backup.createNewFile();
      fileCopy(dbFile, backup);
    } catch (IOException e) {
      /*Handle File Error*/ 
    }

private void fileCopy(File source, File dest) throws IOException {
      FileChannel inChannel = new FileInputStream(source).getChannel();
      FileChannel outChannel = new FileOutputStream(dest).getChannel();
      try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
      } finally {
        if (inChannel != null) inChannel.close();
        if (outChannel != null) outChannel.close();
      }
    }

它设法创建了一个目录名“myappsbackup”但我的数据库无法复制。它总是大小为0,我的表格丢失了。我的复制方法有问题吗?

1 个答案:

答案 0 :(得分:0)

以下是我用来将我的SQLite数据库写入或备份到SD卡的代码。

try {
 db.open();
 File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");

        OutputStream output = new FileOutputStream(newFile);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        output.flush();
        output.close();
        input.close();
        db.close();

    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }