Is it possible to save database file to SD card? [duplicate]

时间秒杀一切 提交于 2019-12-01 12:15:24

Yes. Here is the function that i use:

public void copyDBToSDCard() {
    try {
        InputStream myInput = new FileInputStream("/data/data/com.myproject/databases/"+DATABASE_NAME);

        File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                Log.i("FO","File creation failed for " + file);
            }
        }

        OutputStream myOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
        Log.i("FO","copied");

    } catch (Exception e) {
        Log.i("FO","exception="+e);
    }


}

For a project that I worked on, I put a menu option in the home screen that I could call this function from at any time. Then, I'd move the database to my desktop and open it up with the SQLite Manager plugin for FireFox.

Sure. If this is a database that exists in your app, you can get a reference to the db file via Context.getDatabasePath(), passing it the database name. From there, it's just a routine file copy operation:

//Get a reference to the database
File dbFile = mContext.getDatabasePath("mydb");
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
  exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];

//Attempt file copy
try {
  backup.createNewFile();
  fileCopy(dbFile, backup);
} catch (IOException e) {
  /*Handle File Error*/
}

Where the method fileCopy() is defined as:

private void fileCopy(File source, File dest) throws IOException {
  FileChannel inChannel = new FileInputStream(source).getChannel();
  FileChannel outChannel = new FileOutputStream(dest).getChannel();
  try {
    inChannel.transferTo(0, inChannel.size(), outChannel);
  } finally {
    if (inChannel != null) inChannel.close();
    if (outChannel != null) outChannel.close();
  }
}

HTH!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!