我想通过代码将数据库导出到SD卡,但它不会在SD卡中创建db文件

时间:2016-11-26 06:53:58

标签: java android-studio

请帮助我,我该怎么办。 我想通过代码将数据库导出到SD卡,但它不会在SD卡中创建db文件。

我试过的代码。

 // error in getting the " File dir = new File(getStorageBasedirectory().getAbsolutePath+ "/backup");"
 public File getBackupData`enter code here`baseFile() {
        File dir = new File(Environment.getExternalStorageDirectory()+ "/backup");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return new File(dir, DATABASE_NAME);
    }
    public final boolean backupDatabase() {
        File from = context.getDatabasePath(DATABASE_NAME);
        File to = this.getBackupDatabaseFile();
        try {
            FileUtils.copyFile(from, to);
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Toast.makeText(context, "Error while copying file", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
    public static void copyFile(File src, File dst) throws IOException {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dst);
        FileChannel fromChannel = null, toChannel = null;
        try {
            fromChannel = in.getChannel();
            toChannel = out.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            if (fromChannel != null)
                fromChannel.close();
            if (toChannel != null)
                toChannel.close();
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这段代码

try {
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();

    if (sd.canWrite()) {
        String currentDBPath = "//data//{package name}//databases//{database name}";
        String backupDBPath = "{database name}";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) {
            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
        }
    }
} catch (Exception e) {
}