Download file from url on adroid

1

I'm trying to get a file through a URL and I want to put it in a variable file, I've tried something like this:

URL url = new URL ("http://camporeal.tv/Examen.docx");
URLConnection urlCon = url.openConnection();
InputStream is = urlCon.getInputStream();
FileOutputStream fos = new FileOutputStream("/storage/emulated/0/Ejemplo11111111111122222222.docx");
byte [] array = new byte[1000];
int leido = is.read(array);
while (leido > 0) {
    fos.write(array,0,leido);
    leido=is.read(array);
}
is.close();
fos.close();

But nothing.

    
asked by juanjo 22.05.2018 в 11:52
source

1 answer

0

Save file from an url on Android.

For this you need to take into account several things,

1) Assign permissions

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

for Android 6.0+ devices the WRITE_EXTERNAL_STORAGE permission must be required manually.

2) Do not define the destination route since the path may not be found on certain devices, it is correct to use the method Environment.getExternalStorageDirectory ()

Environment.getExternalStorageDirectory() + "/Ejemplo.docx

in this way the route will be obtained: /storage/emulated/0/Ejemplo.docx

3) Use an Asynctask to avoid operations in the main Thread to avoid NetworkonMainThreadException .

This would be an Asynctask to which you send the url of the file to be downloaded and the route in which you wish to write the file, contains the permission request:

   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!");
            }
        }
    }

To call this AsyncTask simply define the context, the url of the file to be downloaded and the destination path:

  new DownloadFile(this).execute("http://camporeal.tv/Examen.docx", Environment.getExternalStorageDirectory() + "/Ejemplo.docx");
    
answered by 22.05.2018 в 18:48