Android download file to sd card

Source: Internet
Author: User

HttpURLConnection Upload Method:

Try to understand the differences between the two streams:

InputStreamReader Read mode:
1 //Create a URL object2URL url =NewURL (urlstring);3  4 //Create a HttpURLConnection5Httpurlconnetion Urlconn =(HttpURLConnection) Url.openconnecton ();6  7 //reading Data8Bufferreader buffer =NewBufferreader (NewInputStreamReader (Urlconn.getinputstream ()));9StringBuffer SB =NULL;TenString line =NULL; One  while(line = Buffer.readline ())! =NULL){ A Sb.append (line); -}
InputStream Read mode:
//Create a URL objectURL url =NewURL (urlstring);//Create a HttpURLConnectionhttpurlconnection urlconn = (httpurlconnection) url.openconnection ();//get a InputStreamInputStream InputStream =Urlconn.getinputstream ();//get the path to the SD cardString Sdpath = environment.getexternalstoragedirectory () + "/";//Create a folder to useFile dir =NewFile (Sdpath +dirName);d ir.mkdirs ();//Create an output fileFile File =NewFile (Sdpath + dirName +fileName); File.createnewfile ();//Create a file output streamOutputStream output =Newfileoutputstream (file);//Building Buffersbyte[] buffer =New byte[1*1024];//Stream Read IndexintDownloadnum = 0; //writes an input stream to a file while((Downloadnum = inputstream.read (buffer))! =-1) {output.write (buffer,0, downloadnum);} Output.flush ();

When the file is downloaded to the SD card, output.write (buffer); This code is absolutely problematic and causes the file to become corrupted. So take care of it.
Because assuming that you read 40kb of data every time for a 76kb file, the last time you read buffer, there's only 76-40=36kb.
However, you still write 40KB data inside the file, resulting in a 4kb of blank data at the end of the file, which can sometimes affect the reading of the file, but at least the file is still a file containing the full data

Android download file to sd card

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.