Attempting to copy SQLite database from data to SD card

I am using the following code that was placed somewhere in Stack and modified for my purposes:

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

Thus, the error that I get when trying to get to it is:

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

I am trying to copy this file without using my tablet. The application has permission to write to the external storage address; I just can't get around this error. Thank you for your help in resolving this problem, it infuriated me.

+4
source share
2 answers

You use "MY_DATABASE" literally when you probably really want to use it as a variable ...

Remove the quotation marks around it and see if your problem solves.

+2
source

I maintain my database in my Android app and it works great. You can only access the database file if you own it, that is, your application created it.

I think your path is wrong, I have this in my application:

 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; } 

And 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(); } } 
+4
source

All Articles