Android: How to download a file in Android?

I am trying to download a file from a url. I have the following code.

package com.example.downloadfile; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.widget.TextView; import android.widget.Toast; public class DownloadFile extends Activity { private static String fileName = "al.jpg"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = new TextView(this); tv.setText("This is download file program... "); try { //this is the file you want to download from the remote server String path ="http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg"; //this is the name of the local file you will create String targetFileName = "al.jpg"; boolean eof = false; URL u = new URL(path); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); String PATH_op = Environment.getExternalStorageDirectory() + "/download/" + targetFileName; tv.append("\nPath > " + PATH_op); FileOutputStream f = new FileOutputStream(new File(PATH_op)); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ( (len1 = in.read(buffer)) > 0 ) { f.write(buffer,0, len1); } f.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } tv.append("\nAnother append!"); this.setContentView(tv); } } 

Can someone tell me what is wrong with this code. I can not see the file that should download. I am new to java and android dev, thanks a lot for any help. :)

+6
source share
3 answers
  • You do network I / O in the main thread of the application. At best, this will freeze your user interface at boot time. In the worst case scenario, you will encounter a situation with the Application Not Responding (ANR) dialog box.

  • You are trying to write to a directory ( download/ ) on external storage that may not exist. Create a directory first.

  • Please proceed to use Log.e() to log errors, since I do not know if printStackTrace() works on Android.

Also, make sure you have WRITE_EXTERNAL_STORAGE permission and that you are using adb logcat , DDMS or the DDMS perspective in Eclipse to check LogCat and look for error messages that you are trying to execute.

+7
source

First, you must add permissions for AndroidManifest.xml:

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

Secondly, add this code so that if the folder does not exist, it checks and creates the folder:

 File root = android.os.Environment.getExternalStorageDirectory(); File dir = new File (root.getAbsolutePath() + "/download"); if(!dir.exists()) { dir.mkdirs(); } 

Third, as Commons Ware reports, loading into the main thread is not good practice; You must implement it on a new thread; because at boot time the main thread is busy loading the file. If the wait time is longer than expected, the system will generate a Do Not Respond error.

For this you can use TaskAsync "or" IntentService "or even creating a new thread.

As you said, you are new to java, I suggest using " TaskAsync ", as it is very simple and easy.

+2
source

lib will help you

https://github.com/AriaLyy/Aria

download file only one code

 Aria.download(this) .load(DOWNLOAD_URL) .setDownloadPath(DOWNLOAD_PATH) //file save path .add(); 

get boot status

 @Download.onPre(DOWNLOAD_URL) protected void onPre(DownloadTask task) {} @Download.onTaskStart void taskStart(DownloadTask task) {} @Download.onTaskRunning protected void running(DownloadTask task) {} @Download.onTaskResume void taskResume(DownloadTask task) {} @Download.onTaskStop void taskStop(DownloadTask task) {} @Download.onTaskCancel void taskCancel(DownloadTask task) {} @Download.onTaskFail void taskFail(DownloadTask task) {} @Download.onTaskComplete void taskComplete(DownloadTask task) {} @Download.onNoSupportBreakPoint public void onNoSupportBreakPoint(DownloadTask task) {} 
+1
source

Source: https://habr.com/ru/post/887264/


All Articles