Android File Download

Source: Internet
Author: User

Download. in Java, the main body of the program is put, and in the util package, some common methods are put, among which fileutils. java puts some basic operations on the file, httpdownloader. java provides some basic download operations.

 

Step 1: first look at the main program section

Package Mars. download; import Mars. util. httpdownloader; import android. app. activity; import android. OS. bundle; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; public class download extends activity implements onclicklistener {/** called when the activity is first created. */private button downloadtxtbutton; private button downloadmp3b Utton; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); findview ();} public void findview () {downloadtxtbutton = (button) findviewbyid (R. id. downloadtxt); downloadtxtbutton. setonclicklistener (this); downloadmp3button = (button) findviewbyid (R. id. downloadmp3); downloadmp3button. setonclicklistener (this) ;}@ overridepublic void onclick (V Iew v) {// todo auto-generated method stubint viewid = v. GETID (); Switch (viewid) {/*** this method can only Download text files, which are read row by row. */Case R. id. downloadtxt: {httpdownloader = new httpdownloader (); string LRC = httpdownloader. downstr ("http: // 61.184.100.229/"); // you can customize the log for the URL in this region. E ("@", "downloadtxt:" + LRC) ;}/ *** this method can download any file. */Case R. id. downloadmp3: {httpdownloader = new httpdownloader (); int result = httpdownloader. downfile ("http: // 192.168.1.107: 8080/voa1500/a1.mp3", "VOA/", "a1.mp3"); // you can define the log for URLs in this region. E ("@", "downloadmp3");} default: Break ;}}}

 

Step 2: Check the basic operations on the files in the sdcard.

Package Mars. util; 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; Public String getsdpath () {return sdpath;} public fileutils () {// get the directory of the current sdcard storage device/sdcard, environment. getexternalstoragedirectory () This method is more common sdpath = environment. getexternalstor Agedirectory () + "/";}/*** create a file on the SD card */Public file creatsdfile (string filename) throws ioexception {file = new file (sdpath + filename); file. createnewfile (); Return file;}/*** create directory on SD card */Public file creatsddir (string dirname) {file dir = new file (sdpath + dirname); Dir. mkdir (); Return dir;}/*** determines whether the folder on the SD card exists */Public Boolean isfileexist (string filename) {file = new file (sdpath + filename ); Return file. exists ();}/*** write data in an inputstream to the SD card */Public file write2sdfrominput (string path, string filename, inputstream input) {file = NULL; outputstream output = NULL; try // The fixed method of writing data in inputstream to the SD card {creatsddir (PATH); file = creatsdfile (path + filename ); output = new fileoutputstream (File); byte buffer [] = new byte [4*1024]; while (input. read (buffer ))! =-1) {output. write (buffer);} output. flush ();} catch (exception e) {e. printstacktrace ();} finally {try {output. close ();} catch (exception e) {e. printstacktrace () ;}} return file ;}}

 

Step 3: Basic download operations

Package Mars. util; 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 {/*** download a file based on the URL, provided that the content in the file is text, and the return value of the function is the content in the file * 1. create a URL object * 2. create an httpurlconnection object through a URL object * 3. obtain inputstram * 4. from inputs Read data in tream */Private URL url = NULL; Public String downstr (string urlstr) // The method for downloading the response stream {/*** string and stringbuffer can both store and manipulate strings, that is, string data containing multiple characters. * The string class is a String constant and cannot be changed. Stringbuffer is a string variable, and its objects can be expanded and modified. */Stringbuffer sb = new stringbuffer (); string line = NULL; bufferedreader buffer = NULL; // The bufferedreader class is used to read the content from the buffer. Try {/*** because it is not easy to use inputstream directly. It is usually nested with bufferedreader, which is a fixed format for reading the response stream. */Url = new URL (urlstr); // create a URL object httpurlconnection urlconn = (httpurlconnection) URL. openconnection (); // create an HTTP connection buffer = new bufferedreader (New inputstreamreader (urlconn. getinputstream (); // use the IO stream to read data while (line = buffer. readline ())! = NULL) {sb. append (line) ;}} catch (exception e) {e. printstacktrace ();} finally {try {buffer. close ();} catch (exception e) {e. printstacktrace () ;}} return sb. tostring ();}/***-1: Indicates An error occurred while downloading the object. * 0: indicates that the object has been downloaded successfully. * 1: indicates that the object already exists */Public int downfile (string urlstr, string path, string filename) // Method for downloading files {inputstream = NULL; try {fileutils = new fileutils (); If (fileutils. isfileexist (path + filename) {return 1;} else {inputstream = getinputstreamfromurl (urlstr); file resultfile = fileutils. write2sdfrominput (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 input stream based on the URL */Public inputstream getinputstreamfromurl (string urlstr) throws malformedurlexception, ioexception {url = new URL (urlstr ); // create a URL object httpurlconnection urlconn = (httpurlconnection) URL. openconnection (); // create an HTTP connection inputstream = urlconn. getinputstream (); // get the input stream return inputstream ;}}

 

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.