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