尝试将SQLite DB从数据复制到SD卡

时间:2012-06-15 00:29:10

标签: android sqlite copy android-sdcard

我正在使用以下代码在Stack Overflow上发布并为我的目的进行了修改:

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

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+ "com.exercise.AndroidSQLite" +"//databases//"+"MY_DATABASE";
            String backupDBPath = "/temp/MY_DATABASE";
            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();


    }
}

因此,当我尝试访问它时出现的错误是:

java.io.FileNotFoundException: /data/data/com.exercise.AndroidSQLite/databases/MY_DATABASE: open failed: EACCES (Permission Denied)

我正在尝试复制此文件而不会使我的平板电脑生根。写入外部存储目录权限在应用程序中设置;我无法绕过这个错误。非常感谢帮助解决这个问题,这让我很生气

2 个答案:

答案 0 :(得分:4)

我在我的Android应用程序中备份我的数据库,它工作正常。如果您是数据库文件的所有者,则只能访问数据库文件,这意味着您的应用程序已创建它。

我认为你的道路是错的,我在我的应用程序中有这个:

private static final String DATABASE_NAME = "my.db.name";

public File getBackupDatabaseFile() {
    File dir = new File(getStorageBaseDirectory().getAbsolutePath() + "/backup");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    return new File(dir, DATABASE_NAME);
}
public final boolean backupDatabase() {
    File from = mContext.getDatabasePath(DATABASE_NAME);
    File to = this.getBackupDatabaseFile();
    try {
        FileUtils.copyFile(from, to);
        return true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
       Log.e(TAG, "Error backuping up database: " + e.getMessage(), e);
    }
    return false;
}

FileUtils.copyFIle是这样的:

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 :(得分:2)

当您可能真的想将它用作变量时,您正在使用“MY_DATABASE”......

从中删除引号,看看是否无法解决您的问题。

相关问题