Guardar archivo desde una url en Android.
Para esto necesitas tener en cuenta varias cosas,
1) Asignar permisos
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
para dispositivos con Android 6.0+ el permiso WRITE_EXTERNAL_STORAGE debe ser requerido manualmente.
2) No definas la ruta destino ya que el path puede no encontrarse en ciertos dispositivos, lo correcto es usar el método Environment.getExternalStorageDirectory()
Environment.getExternalStorageDirectory() + "/Ejemplo.docx
de esta forma se obtendrá la ruta: /storage/emulated/0/Ejemplo.docx
3) Usa un Asynctask para evitar operaciones en el Thread principal para evitar NetworkonMainThreadException.
Este sería un Asynctask al cual le envias la url del archivo a descargar y la ruta en la que deseas se escriba el archivo, contiene la petición de permisos:
public class DownloadFile extends AsyncTask<String, Void, Boolean> {
private Context mContext;
public DownloadFile (Context context){
mContext = context;
}
@Override
protected Boolean doInBackground(String... strings) {
try {
//Verifica permisos para Android 6.0+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
checkExternalStoragePermission();
}
//Url de descarga
String url = strings[0];
//Path destino
String outputPath = strings[1];
Log.i(TAG, "* Url source: " + url);
Log.i(TAG, "* output Path: " + outputPath);
File outputFile = new File(outputPath);
HttpURLConnection conn = null;
URL u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
Log.e(TAG, "* FileNotFoundException: " + e.getMessage());
return false; // swallow a 404
} catch (IOException e) {
Log.e(TAG, "* IOException: " + e.getMessage());
return false; // swallow a 404
}
return true;
}
private void checkExternalStoragePermission() {
int permissionCheck = ContextCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "No se tiene permiso para leer.");
ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
} else {
Log.i(TAG, "Se tiene permiso para leer!");
}
}
}
Para llamar este AsyncTask
simplemente define el contexto, la url del archivo a descargar y el path destino:
new DownloadFile(this).execute("http://camporeal.tv/Examen.docx", Environment.getExternalStorageDirectory() + "/Ejemplo.docx");