Android - Can not find the file although it exists

2019-07-14 16:29发布

问题:

I am trying to copy the SQLite database from the data folder to SDCard using Emulator, i am using below code, which i found here.

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

    if (sd.canWrite()) {
        String currentDBPath = "\\data\\PackageName\\databases\\myDB.db";
        String backupDBPath = "myDB.db";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) 
        {
           // code to copy from currentDB  to backupDB 
        }
    }
} catch (Exception e) {
}

For write permission below is also added to manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Issue:

The issue is that the "currentDB.exists()" returns FALSE.

The "currentDB.getAbsolutePath()" returns the path which is "data\data\PackageName\databases\myDB.db"

This is the correct location of the database, because i can find it using Eclipse >> DDMS perspective >> File Explorer

Can somebody help me find the issue why the "currentDB.exists()" returns FALSE?

Thanks for your valuable time & help.

回答1:

Well guys i just removed the ".db" extension & it works now! See the updated code below:

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

    if (sd.canWrite()) {
        String currentDBPath = "\\data\\PackageName\\databases\\myDB";
        String backupDBPath = "myDB";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) 
        {
           // code to copy from currentDB  to backupDB 
        }
    }
} catch (Exception e) {
}

myDB.db is replaced with "myDB".