move database to External Storage Directory - Android Database

Android examples for Database:Database Backup

Description

move database to External Storage Directory

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import android.os.Environment;
import android.util.Log;

public class Main {
    public static void moveDBtoSD(String name) {
        try {//from   w w w.  ja v  a2  s. c  o  m
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//databases//"
                        + name;
                String backupDBPath = name;
                Log.d("DEBUG", backupDBPath);

                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB)
                            .getChannel();
                    FileChannel dst = new FileOutputStream(backupDB)
                            .getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {
            Log.d("SD", "Error moviendo la db error:" + e.getMessage());
        }
    }
}

Related Tutorials