Tool Class Fileutils.java
Package com.example.filedownload_01;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 current external storage device directory general is/sdcardsdpath = Environment.getexternalstoragedirectory () + "/";} /** * Create file * @param fileName filename * @return Newly created file on SD card * @throws ioexception */public file createsdfile (string filename) throws ioexception {file file = new file (Sdpath + filename); File.createnewfile (); return file;} /** * creating a directory on an SD card * @param dirName directory name * @return */public file createsddir (String diRname) {file dir = new file (sdpath + dirname);d ir.mkdir (); return dir;} /** * determine if there are files * @param fileName * @return on the SD card */public boolean isfileexist (String filename) {file file = new file (SDPATH + FileName); return file.exists ();} /** * writes data from a inputstream to the SD card * @param path paths * @param filename file name * @param input input stream * @return writing files to sd card */public File write2sdfrominput (string path, string filename, inputstream input) { File file = null;outputstream output = null;try {createsddir (path); file = createsdfile (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 e2) {e2.printstacktrace ();}} Return file;}}
httpdownloader.java
Package com.example.filedownload_01;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;import Org.apache.http.message.bufferedheader;public class httpdownloader {private url url = null;public string download (STRING URLSTR) {StringBuffer sb = New stringbuffer (); string line = null; Bufferedreader buffer = null;try {url = new url (URLSTR); httpurlconnection urlconnection = (HttpURLConnection) url.openconnection (); buffer = new bufferedreader (New inputstreamreader (Urlconnection.getinputstream ()));while (line = buffer.readline ()) != null) {sb.append (line);}} catch (EXCeption e) {e.printstacktrace ();} finally {try {buffer.close ();} catch (Exception e2) {e2.printstacktrace ();}} Return sb.tostring ();} /** * @param urlStr * url * @param path * Save Paths * @param fileName * file name * @return return value-1: Error downloading file, 0 indicates successful download, 1 means file already exists */public int DownloadFile (String urlstr, string path, string filename) {InputStream Inputstream = null;try {fileutils fileutils = new fileutils ();if ( Fileutils.isfileexist (path + filename)) {return 1;// file already exists} 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;} Public inputstream getinputstreamfromurl (STRING URLSTR) throws ioexception {url = new url (URLSTR); httpurlconnection urlconnection = (HttpURLConnection) url.openconnection (); InputStream inputstream = urlconnection.getinputstream (); return inputstream;}}
Mainactivity.java
package com.example.filedownload_01;import android.support.v7.app.actionbaractivity;import Android. r.integer;import android.os.bundle;import android.os.handler;import android.os.handlerthread; import android.os.looper;import android.os.message;import android.view.menu;import android.view.menuitem;import android.view.view;import android.view.view.onclicklistener;import android.widget.button;import android.widget.toast;public class mainactivity extends actionbaractivity {private button downloadtxtbutton = null;private button downloadmp3button = null; @Overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);d ownloadmp3button = (Button) findviewbyid (R.id.downloadmp3button);d ownloadtxtbutton = (button) Findviewbyid (r.id.downloadtxtbutton);d Ownloadtxtbutton.setonclicklistener (New downloadtextlistener ()); Downloadmp3button.setonclicklistener (New downloadmp3listener ());} class downloadtextlistener implements onclicklistener {@Overridepublic void OnClick (VIEW V) {system.out.println ("Download txt file"); Toast.maketext (mainactivity.this, "start to download txt", toast.length_short). Show (); string urlstr = "HTTP://WWW.51VOA.COM/LRC/201411/SE-HEALTH-SURGICAL-SAFARI-COSMETIC-18NOV14.LRC "; string path = "umgsai_download/"; string filename = "TEST.LRC";//generates a Handlerthread object that implements the function of using looper to process Message Queuing handlerthread handlerthread = new handlerthread ("Handler_ Thread "); handlerthread.start (); myhandler myhandler = new myhandler (Handlerthread.getlooper ()); &nbsP; message msg = myhandler.obtainmessage (); //msg.obj = "ABC"; //Simple Data Bundle bundle = new bundle (); Bundle.putstring ("Urlstr", urlstr); bundle.putstring (" FileName ", filename); bundle.putstring (" Path ", path); msg.setdata (bundle); //sends MSG to the target object, which is the handler object that generates the MSG object msg.sendtotarget ();// Httpdownloader httpdownloader = new httpdownloader ();//string lrc = Httpdownloader.download ("Http://localhost/menu/log.txt");//system.out.println (LRC);}} class downloadmp3listener implements onclicklistener{@OvErridepublic void onclick (VIEW V) {//httpdownloader httpdownloader = new httpdownloader ();//int result = httpdownloader.downloadfile (", " voa/", " Test.mp3 ");//system.out.println (result); Toast.maketext (mainactivity.this, "Start Download MP3", toast.length_short). Show (); string urlstr = "http://127.0.0.1/menu/test.apk"; string path = "umgsai_download/"; string filename = "test.apk";//generates a Handlerthread object that implements the function of using looper to process Message Queuing handlerthread handlerthread = new handlerthread ("Handler_ Thread "); handlerthread.start (); myhandler myhandler = new myhandler (Handlerthread.getlooper ()); message msg = myhandler.obtainmessage (); //msg.obj = "ABC"; //Simple Data Bundle bundle = new bundle (); Bundle.putstring ("Urlstr", urlstr); bundle.putstring (" FileName ", filename); bundle.putstring (" Path ", path); msg.setdata (bundle); //sends MSG to the target object, which is the handler object that generates the MSG object msg.sendtotarget ();}} Class myhandler extends handler{public myhandler () {}public myhandler (Looper looper) {super (Looper);} @Overridepublic void handlemessage (message msg) {super.handlemessage (msg); Bundle bundle = msg.getdata (); String urlstr = bundle.getstring ("Urlstr"); string filename = bundle.getstring ("FileName"); String path = bundle.getstring ("path"); Httpdownloader httpdownloader = new httpdownloader ();int result = Httpdownloader.downloadfile (Urlstr, path, filename); SYSTEM.OUT.PRINTLN (result); Toast.maketext (mainactivity.this, "~", toast.length_short). Show ();//string lrc = Httpdownloader.download (FileName);//system.out.println (LRC);}}}
The task of downloading the file cannot be placed inside the main thread, otherwise it will throw an exception.
There was a problem downloading the MP3 file and it was not resolved.
This article is from "Avatar" blog, please make sure to keep this source http://shamrock.blog.51cto.com/2079212/1580269
Android Learning notes-File download