gpt4 book ai didi

android - 尝试将 SQLite 数据库从数据复制到 SD 卡

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:48 24 4
gpt4 key购买 nike

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

我想在不对平板电脑进行 root 的情况下复制此文件。应用中设置写外部存储目录权限;我只是无法解决这个错误。非常感谢帮助解决这个问题,这让我很生气

最佳答案

我在我的 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();
}
}

关于android - 尝试将 SQLite 数据库从数据复制到 SD 卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com