Android downloads files to sd card based on URL

Source: Internet
Author: User

  1. Download Specific actions
  2. private void Download () {
  3. try {
  4. URL url = new URL (downloadurl);
  5. Open connection
  6. URLConnection conn = url.openconnection ();
  7. Open input Stream
  8. InputStream is = conn.getinputstream ();
  9. Get length
  10. int contentlength = conn.getcontentlength ();
  11. LOG.E (TAG, "contentlength =" + contentlength);
  12. Create a folder Mydownload, under the memory card
  13. String dirName = environment.getexternalstoragedirectory () + "/mydownload/";
  14. File file = new file (DirName);
  15. does not exist create
  16. if (!file.exists ()) {
  17. File.mkdir ();
  18. }
  19. The file name after download
  20. String fileName = dirName + "xiaomibianqian.apk";
  21. File file1 = new File (FileName);
  22. if (file1.exists ()) {
  23. File1.delete ();
  24. }
  25. Create a byte stream
  26. byte[] bs = new byte[1024];
  27. int Len;
  28. OutputStream os = new FileOutputStream (FileName);
  29. Write Data
  30. while (len = is.read (BS))! =-1) {
  31. Os.write (BS, 0, Len);
  32. }
  33. Close the stream when finished
  34. LOG.E (TAG, "download-finish");
  35. Os.close ();
  36. Is.close ();
  37. } catch (Exception e) {
  38. E.printstacktrace ();
  39. }
  40. }
  41. }
  42. String dirName = environment.getexternalstoragedirectory () + "/mydownload/";
  43. <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android: Name= "Android.permission.READ_EXTERNAL_STORAGE"/>

Android downloads files to sd card based on URL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.