Use http to download files and write them to the SD card
Download steps:
1. Create an httpurlconnection object
Httpurlconnection urlconn =
(Httpurlconnection) URL. openconnection ();
2. Obtain an inputstream object
Urlconn. getinoutstream ()
3. Set Network Access Permissions (set in the manifest file)
Android. Permission. Internet
Access SD card:
1. Get the directory of the SD card
Environment. getexternalstoragedirectory ()
2. SD card access permissions:
Android. Permission. write_external_storage
Note: Do not forget to set permissions.
Manifest. xml file:
<? XML version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "Mars. download "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <uses-SDK Android: minsdkversion =" 4 "/> <application Android: icon = "@ drawable/ic_launcher" Android: Label = "@ string/app_name"> <activity Android: Label = "@ string/app_name" Android: Name = ". downloadactivity "> <intent-filter> <action Android: Name =" android. intent. Action. Main "/> <category Android: Name =" android. Intent. Category. launcher "/> </intent-filter> </activity> </Application> <! -- Set the network download permission and SD card write permission --> <uses-Permission Android: Name = "android. permission. internet "/> <uses-Permission Android: Name =" android. permission. write_external_storage "/> </manifest>
Downloadactivity. Java:
package mars.download;import mars.utils.HttpDownloader;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class DownloadActivity extends Activity { /** Called when the activity is first created. */private Button downloadTxtButton;private Button downloadMp3Button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadTxtButton = (Button)findViewById(R.id.downloadTxt); downloadMp3Button = (Button)findViewById(R.id.downloadMp3); downloadTxtButton.setOnClickListener(new DownLoadTxtListener()); downloadMp3Button.setOnClickListener(new DownLoadMp3Listener()); }class DownLoadTxtListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubHttpDownloader httpDownloader = new HttpDownloader();String str = httpDownloader.download("http://ishare.sina.cn/download.php?action=loading&id=13912266&cid=05_14&p=1");System.out.println("Download");System.out.println(str);}}class DownLoadMp3Listener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString urlStr = "http://ishare.sina.cn/download.php?action=loading&id=13912266&cid=05_14&p=1";HttpDownloader httpDownloader = new HttpDownloader();int state = httpDownloader.downFile(urlStr, "voa/", "myFile");System.out.println(state);}}}
Httpdownloader. Java:
Package Mars. utils; import Java. io. bufferedreader; import Java. io. file; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import java.net. httpurlconnection; import java.net. malformedurlexception; import java.net. URL; public class httpdownloader {Private URL url = NULL;/*** download the file according to the URL * 1. create a URL object * 2. create an httpurlconnection object through a URL object * 3. obtain inputstream * 4. from inputstr Read data from EAM * // download Public String download (string urlstr) {stringbuffer sb = new stringbuffer (); string line = NULL; bufferedreader buffer = NULL; try {// create a URL object url = new URL (urlstr); // create an HTTP connection httpurlconnection urlconn = (httpurlconnection) URL. openconnection (); // use the IO stream to read data/*** urlconn. getinputstream () obtains the byte stream * sets a layer of inputstreamreader to get the response stream * sets a layer of bufferedreader to get the response stream. Then, you can use Readline to read data by row */buffer = ne W bufferedreader (New inputstreamreader (urlconn. getinputstream (); While (line = buffer. Readline ())! = NULL) {sb. append (line) ;}} catch (exception e) {system. out. println ("error"); E. printstacktrace ();} finally {try {buffer. close ();} catch (exception e) {e. printstacktrace () ;}} return sb. tostring ();} // download the file and write it to the SD card. // parameter: URL address, absolute path of the file storage directory, public int downfile (string urlstr, string path, string filename) {inputstream = NULL; try {fileutils = new fileutils (); // if the file already exists, 1if (fileutils. isfileexist (path + filename) {return 1;} else {// get the file input stream inputstream = getinputstreamfromurl (urlstr) based on the URL; // write the input stream to the SD card, for detailed procedures, see fileutils. javafile resultfile = fileutils. writesdfrominput (path, filename, inputstream); If (resultfile = NULL) {return-1 ;}} catch (exception e) {e. printstacktrace (); Return-1;} finally {try {inputstream. close ();} catch (exception e) {e. printstacktrace () ;}} return 0;} // get the file input stream public inputstream getinputstreamfromurl (string urlstr) throws malformedurlexception, ioexception {url = new URL (urlstr) based on the URL ); httpurlconnection urlconn = (httpurlconnection) URL. openconnection (); inputstream = urlconn. getinputstream (); Return inputstream ;}}
Fileutils. Java:
Package Mars. utils; import Java. io. file; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import android. OS. environment;/*** this class is the encapsulation of operating SD card files * including determining whether a file (folder) exists, creating a file (folder ), write the file stream to the file ** @ author administrator **/public class fileutils {// the path of the SD card is private string sdpath; Public String getsdpath () {return sdpath;} public fileutils () {// obtain the directory sdpat of the current external storage device H = environment. getexternalstoragedirectory () + "/";}/*** create a file on the SD card **/Public file createsdfile (string filename) throws ioexception {// obtain the file object file = new file (sdpath + filename) based on the full path name of the file; // create a file. createnewfile (); Return file;}/*** create directory on SD card */Public file createsddir (string dirname) {file dir = new file (sdpath + dirname); Dir. mkdir (); Return dir;}/*** determines whether a folder exists */Public Boolean isfileexist (string Filename) {file = new file (sdpath + filename); Return file. exists ();}/*** write data in an inputstream to the SD card * // parameter: file storage path (absolute directory path), file name, input stream public file writesdfrominput (string path, string filename, inputstream input) {file = NULL; outputstream output = NULL; try {// create the file storage directory createsddir (PATH ); // create file = createsdfile (path + filename); // obtain the output stream output of the new file = new fileoutputstream (File); // buffer byte buffer [] = new Byte [4*1024]; // read data from the input stream in sequence and output it to the file. Each time, four bytes of while (input. Read (buffer) are read ))! =-1) {output. write (buffer);} // clear the cache output. flush ();} catch (exception e) {e. printstacktrace ();} finally {try {// close the output stream output. close ();} catch (exception e) {e. printstacktrace () ;}} return file ;}}