How to copy a Sqlite database or file from internal storage to external storage?


How to copy a file or database from internal to external storage, sometimes we need to read files inside the internal storage ( data/data ), which is only possible if the device has root permission.

In the case of a device that does not have these permissions, it is impossible to access the information.

asked by Elenasys 15.06.2017 в 22:33

1 answer


I suggest this method

public static boolean copyFile(String from, String to) {
    boolean result = false;
        File dir = new File(to.substring(0, to.lastIndexOf('/')));
        File tof = new File(dir, to.substring(to.lastIndexOf('/') + 1));
        int byteread;
        File oldfile = new File(from);
            InputStream inStream = new FileInputStream(from);
            FileOutputStream fs = new FileOutputStream(tof);
            byte[] buffer = new byte[1024];
            while((byteread = != -1){
                fs.write(buffer, 0, byteread);
        result = true;
    }catch (Exception e){
        Log.e("copyFile", "Error copiando archivo: " + e.getMessage());
    return result;

which would be called in this way, knowing the package of your application and the name of the file or database saved, indicate source and destination of the file to be copied:

//Obtiene ruta de base de datos origen.
String pathDB = getDatabasePath(NOMBRE_DATABASE).toString();
//Copia base de datos a destino definido.
copyFile(pathDB, Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/" + <nombre archivo destino>);

Do not forget to add permission to write to external storage:

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

With this method you can copy both files and a database to the external storage in order to be able to open the files without problems:

* Important:

to use permission WRITE_EXTERNAL_STORAGE on devices with operating system greater than Android 6.0 (which is implicitly also READ_EXTERNAL_STORAGE ) must be manually requested:

//Verifica permisos para Android 6.0+


Use this method:

private void checkExternalStoragePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        Log.i("Mensaje", "No se tiene permiso para leer.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
    } else {
        Log.i("Mensaje", "Se tiene permiso para leer!");

Review this question:

Error showing the external directory of files in an AlertDialog in android 6.0 (READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE)

answered by 15.06.2017 / 22:33