How to implement file download in Android

Source: Internet
Author: User

Recently do a project need to download pictures from the server to the local sdcard, the Internet to find some examples, the following is more appropriate, the original content is as follows: we often need to download files from the server in development, the content of the download may have Exchange information, cached pictures, program update package and so on. We use URLConnection to implement downloads. Let's look at a few lines of code:String urldownload = ""; urldownload = "Http://www.baidu.com/img/baidu_sylogo1.gif";   URL url = new URL (urldownload); Open connection URLConnection con = url.openconnection ();//input stream InputStream is = Con.getinputstream (); as shown in the code above, specify a download target link, we specify a picture address above. It then constructs a URL object that invokes the object's OpenConnection method to establish a data path (connection). The last line of code uses Con.getinputstream to get an input stream object, through which we can read the contents of this file. The next thing to do is to read the stream and write the stream to our local file. But before we do that, we're going to say this way:<span xmlns= "http://www.w3.org/1999/xhtml" >//get the length of the file int contentlength = Con.getcontentlength (); System.out.println ("Length:" +contentlength) </span> method to get the file length. ContentLength is not very familiar. It is one of the description attributes in the HTTP protocol that describes the header (head) section. Actually here is sent an HTTP request that analyzes the contents of the data returned (response).   we often download files to the phone's memory card, so we also use the method of obtaining the memory card path:<span xmlns= "http://www.w3.org/1999/xhtml" >//gets the memory card path, which forms the destination path of the saved file string dirName = "";d irname = Environment.getexternalstoragedirectory () + "/mydownload/"; File F = new file (dirName), if (!f.exists ()) {F.mkdir ();} </span> The environment.getexternalstoragedirectory () method returns a string that indicates the path of the memory card. We stitch strings out of a folder to prepare the downloaded files. and first determine if the folder is present, or if it does not exist, create a new folder.   after finishing the above preparation, the basic will be able to achieve the download. Let's look at the main complete code.   Pre-Download preparation work:File path to download string urldownload = "";//urldownload = "Http://192.168.3.39/text.txt"; urldownload = "http://www.baidu.com/ Img/baidu_sylogo1.gif ";//Gets the memory card path that forms the destination path of the saved file string dirName =" ";d irname = Environment.getexternalstoragedirectory () + "/mydownload/"; File F = new file (dirName), if (!f.exists ()) {F.mkdir ();} Download the operation: //ready to splice the new file name (the file name saved on the memory card) String NewFileName = _urlstr.substring (_urlstr.lastindexof ("/") +1); NewFileName = _ DirName + newfilename; File File = new file (newfilename);//If the destination file already exists, delete it. Produces an effect that overwrites the old file if (file.exists ()) {    File.delete ();} Try {         //construct URL            url url = new URL (_urlstr);            //Open connection            urlconnection con = ur L.openconnection ();         //Get the length of the file          int contentlength = CON.G Etcontentlength ();        &NBSP;SYSTEM.OUT.PRINTLN ("Length:" +contentlength);         //input stream            inputstream is = Con.getinputstream ();           //1K data buffer            byte[] bs = new byte[1024 ];            //Length of data read            int Len;            //output file stream            outputstream OS = NE W FileOutputStream (NewFileName);            //start reading            while (len = Is.read ( BS))! =-1) {               os.write (BS, 0, Len);            }           //complete, close all links            o S.close ();           is.close ();            } catch (Exception e) {& nbsp       e.printstacktrace ();}   Transfer from:http://www.itivy.com/android/archive/2011/6/28/android-file-download.html  The section of my code is as follows: Download pictures from server to local     private void Getphotofromserver (list<advert> adverts) {   //Read server IP address     String ServerIP = Networkutil.getdns (); Direct read server IP address    //string ServerURL = serverurlall.substring (Serverurlall.indexof (":") +3, Serverurlall.lastindexof (":")); It is best to read the IP address directly from the database or elsewhere     LOG.D (TAG, "Server IP is" + ServerIP);   //integrated into the full advertising image storage directory   &NBSP ; String urldownload = "/http" + ServerIP + ": 8080/propicrecord/";   //advertising image local SD card storage directory     String Dirnam E = "/sdcard/advert/";   //Determine if the directory where the local ad image is stored, does not exist, creates a new folder     file F = new file (dirName);    if ( !f.exists ())     {       f.mkdir ();   }    //server advertising image full path name for download     String Urldownloadall = "";   //Ready to splice New file name (file name saved on memory card)     for (int i=0; Adverts!=null && i<adverts.size (); i++) {            advert advert = aDverts.get (i);           //download path add AD image name             Urldownlo Adall = Urldownload + advert.geturl ();            LOG.D (TAG, "The whole server download URL is "+ Urldownloadall);                       //Get the name of the ad image Word, actually using advert.geturl () can also     String newfilename = urldownloadall.substring (Urldownloadall.lastindexof ("/") + 1);   //The full path of the local broadcast ad image     NewFileName = dirName + newfilename;    LOG.D (TAG, "the is "+ newfilename);       File File = new file (newfilename);   //If the destination file already exists, then delete, resulting in an effect that overwrites the old file (This can be extended later to the already existing picture no longer re-download feature)     if (file.exists ())     {       file.delete ();    }    try{      //structuring url           url URL = new URL (Urldownloadall);          //Open connection            urlconnection con = url.openconnection ();           //Get the length of the file            //int contentlength = Con.getcontentlength () ;          &NBSP;//SYSTEM.OUT.PRINTLN ("Length:" +contentlength);          & nbsp;//input stream            inputstream is = Con.getinputstream ();        &NBSP ;  //1k data buffering            byte[] bs = new byte[1024];          &NBS p;//read data length            int len;           //output file stream   &NBSP ;        outputstream OS = new FileOutputStream (newfilename);           // Start reading            while ((len = Is.read (BS))! =-1) {               os.write (BS, 0, Len);           }           //complete, close all links     &N Bsp      os.close ();           is.close ();   }catch (Exception e) {& nbsp   E.printstacktrace ();   }   }   }
Related Article

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.