I suggest this method
public static boolean copyFile(String from, String to) {
boolean result = false;
try{
File dir = new File(to.substring(0, to.lastIndexOf('/')));
dir.mkdirs();
File tof = new File(dir, to.substring(to.lastIndexOf('/') + 1));
int byteread;
File oldfile = new File(from);
if(oldfile.exists()){
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(tof);
byte[] buffer = new byte[1024];
while((byteread = inStream.read(buffer)) != -1){
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
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+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
checkExternalStoragePermission();
}
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)