开发者

Copied android db file is empty

开发者 https://www.devze.com 2023-03-30 02:28 出处:网络
I\'m trying to copy an android db file from my application folder to another one on SD card. And from DDMS file explorer i can notice that the copied file size is 0. This is my code bellow.

I'm trying to copy an android db file from my application folder to another one on SD card. And from DDMS file explorer i can notice that the copied file size is 0. This is my code bellow.

public boolean copyDBFile(){
    File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
    File exportDir = new File(Environment.getExternalStorageDirectory()
      + "/BACKUP_DIR");
    if (!exportDir.exists()) {
        exportDir.mkdirs();
    }

    File file = new File(exportDir, dbFile.getName());
    try {
        file.createNewFile();           
        copyFile(dbFile, file);
        return true;
    } catch (IOException e) {     
        return false;
  开发者_运维百科  }
}


public void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();

    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
          inChannel.close();
        if (outChannel != null)
          outChannel.close();
    }
}

Is it a permission issue? Thanks for help.


@piyush Thanks for the try/catch notice. I found the error after adding a log trace in boolean copyDBFile() method at catch block.

public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
  + "/BACKUP_DIR");
if (!exportDir.exists()) {
    exportDir.mkdirs();
}

File file = new File(exportDir, dbFile.getName());
try {
    file.createNewFile();           
    copyFile(dbFile, file);
    return true;
} catch (IOException e) {  
    Log.e("Sarelo", "Error creating file", e);
    return false;
}

}

My DB_PATH was already set to /data/data/package/databases/data.db and added to Environment.getDataDirectory() the dbFile result to /data/data/data/package/databases/data.db That's the big mistake! Thanks all for help :)


try using outChannel.force(true); before using the transferTo(...);

0

精彩评论

暂无评论...
验证码 换一张
取 消