Download files for Android development

Source: Internet
Author: User
Tags create directory

Android development, file download must be, in this summary.

Android file download need to prepare: 1, network and read and write SD card permissions settings, 2, httpurlconnection knowledge of the use of, 3, the flow of knowledge to read and write files.

Here is the sample code I wrote myself to understand the Android file download.

1, Androidmainfest.xml

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.example.downloader "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowbackup=" "True" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/ap Ptheme "> <activity android:name=" com.example.downloader.MainActivity "android:label=" @  String/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "         /> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <uses-permission android:name= "Android.permission.INTERNET"/&G          T <uses-permission Android: Name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> </manifest> 

2, Activity_main.xml


<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "    android:layout_width=" fill_parent "    android:layout_height=" Fill_parent "    ><textview      android:layout_width=" fill_parent "     android:layout_height=" Wrap_ Content "     android:text=" Hello "    /><buttonandroid:id=" @+id/buttontxt "android:layout_width=" 300DP " android:layout_height= "Wrap_content" android:text= "click Download txt file"/><buttonandroid:id= "@+id/buttonmp3" Android: Layout_width= "300DP" android:layout_height= "wrap_content" android:text= "click Download mp3 file"/></linearlayout>


3, Mainactivity.java


Package Com.example.downloader;import Android.app.activity;import Android.os.bundle;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {    Private button Buttontxt;private button Buttonmp3; /** called when the activity is first created.        */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        buttontxt= (Button) Findviewbyid (r.id.buttontxt); Add a Click event Listener Buttontxt.setonclicklistener (new Onclicklistener () {/* (non-javadoc) * @see Android.view.View for Buttontxt. Onclicklistener#onclick (Android.view.View) */@Overridepublic void OnClick (view v) {//TODO auto-generated method stub// Create an anonymous thread to download the file New thread () {public void run () {Httpdownloader httpdownloader=new httpdownloader ();// Call the overloaded method of the Httpdownloader object download Download the txt file string txt=httpdownloader.download ("Http://192.168.1.84:8080/Android/1.txt"); SYSTEM.OUT.PRINTLN (TXT);}}.                Start ();}        });        buttonmp3= (Button) Findviewbyid (R.id.buttonmp3); Add a click event listener for Buttonmp3 Buttonmp3.setonclicklistener (new Onclicklistener () {/* (non-javadoc) * @see ANDROID.VI ew. View.onclicklistener#onclick (Android.view.View) */@Overridepublic void OnClick (view v) {//TODO auto-generated method Stubnew Thread () {public void run () {Try{httpdownloader httpdownloader=new httpdownloader ();// Call the overloaded method of the Httpdownloader object download Download the mp3 file int result=httpdownloader.download ("HTTP://192.168.1.84:8080/ANDROID/1. MP3 "," Android/"," Music.mp3 "); SYSTEM.OUT.PRINTLN (result);} catch (Exception e) {e.printstacktrace ();}}}.        Start ();}    }); }}


4, Httpdownloader.java


Package Com.example.downloader;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.URL;public Class Httpdownloader {private URL url=null;public string Download (string urlstr) {StringBuffer stringbuffer=new StringBuffer (); String Line; BufferedReader bufferreader=null;try{//Create a URL object url=new url (urlstr);//Get a HttpURLConnection object httpurlconnection httpurlconnection= (HttpURLConnection) url.openconnection ()//Get IO stream, read data using IO stream bufferreader=new bufferedreader (new InputStreamReader (Httpurlconnection.getinputstream ())); while ((Line=bufferreader.readline ())!=null) { Stringbuffer.append (line);}} catch (Exception e) {e.printstacktrace ();} return stringbuffer.tostring ();} The function returns 1: An error occurred on behalf of the download file; 0: The download file was successful;    1: The representative file already exists public int download (String urlstr,string path,string fileName) {InputStream inputstream=null;    FileUtils fileutils=new FileUtils (); if (fileutils.iseXist (Path+filename)) return 1; else {try {Inputstream=getfromurl (URLSTR)} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktr Ace ();}    File file=fileutils.writetosdpathfrominput (Path, fileName, InputStream); if (file!=null) return 0;else return-1; }}//Get input stream public InputStream Getfromurl (string urlstr) throws IOException {url=new URL (urlstr) based on URL string; H Ttpurlconnection httpurlconnection= (httpurlconnection) url.openconnection (); InputStream input=    Httpurlconnection.getinputstream (); return input; }}

5, Fileutils.java


Package Com.example.downloader;import Java.io.file;import Java.io.fileoutputstream;import java.io.IOException; Import Java.io.inputstream;import Java.io.outputstream;import Android.os.environment;public class FileUtils {private String Sdpath = Null;public string Getsdpath () {return sdpath;} Public FileUtils () {//Get the current external storage device SD Card Directory Sdpath = environment.getexternalstoragedirectory () + "/";} Create file Public createFile (String fileName) throws IOException {File File = new file (Sdpath + fileName); FILE.CREATENEWF Ile (); return file;} Create directory Public file Createdir (String fileName) throws IOException {file Dir = new File (Sdpath + fileName);d ir.mkdir (); retur n dir;} Determines whether the file exists public boolean isexist (String fileName) {File File = new file (Sdpath + fileName); return file.exists ();} Public file Writetosdpathfrominput (string path, String fileName, InputStream inputstream) {File File = Null;outputstream o Utputstream = null;try {createdir (path); file = createFile (path + fileName); outputstream = new FileoutputstrEAM (file); byte buffer[] = new byte[128];//Enter the contents of the input stream into buffer cache, and then write the output stream to the file do {int length = (inputstream.read (buffer)) if (length! =-1) {outputstream.write (buffer, 0, length);} else {break;}} while (true);} catch (Exception e) {e.printstacktrace ();} finally {try {outputstream.close ();} catch (IOException e) {//TODO Auto-genera Ted Catch Blocke.printstacktrace ();}} return file;}}

Note: Network permissions and read-write file permissions are declared in Androidmainfest.xml; activity_ Main.xml in the layout of two buttons, respectively binding set to download the TXT file box for downloading MP3 file events; Httpdownloader.java inside encapsulates the method of getting the stream from the network address; Fileutils.java implementation writes the data from the stream to the file. When writing a file, always pay attention to the buffer size, or it will cause the file to be empty or write failed.



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.