4

我正在使用以下代码,该代码发布在 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)

我正在尝试在不植根平板电脑的情况下复制此文件。写外存目录权限在应用中设置;我只是无法解决这个错误。希望能帮助解决这个问题,这让我发疯

4

2 回答 2

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();
    }
}
于 2012-06-15T00:42:10.370 回答
2

当您可能实际上想将其用作变量时,您实际上是在使用“MY_DATABASE”...

从它周围删除引号,看看这是否不能解决您的问题。

于 2012-06-15T00:40:54.997 回答