To save the file to the SD card, be sure to know the path of the SD card and get the SD card path:
Environment.getexternalstoragedirectory ()
In addition, before saving to determine whether the SD card is installed, and can read and write:
// determine if the sdcard exists and can read and write if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { Service.savetosdcard ( filename,filecontent); Toast.maketext (Getapplicationcontext (), R. string 1 ). Show (); } Else { toast.maketext (Getapplicationcontext (), R. string 1 ). Show (); }
Instance
1. Download the text files and download large-capacity files such as mp3
2. Code writing
Configuration in Androidmainfest.xml
Mainly to resolve network permissions and write SDcard permissions
<?xml version="1.0"encoding="Utf-8"? ><manifest xmlns:android="http://schemas.android.com/apk/res/android" Package="com.jingling.practice.downloadtest"> <uses-permission android:name="Android.permission.INTERNET"/> <uses-permission android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/> <Application Android:allowbackup="true"Android:icon="@drawable/ic_launcher"Android:label="@string/app_name"Android:theme="@style/apptheme"> <Activity Android:name=". 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></manifest>
Package Util;import Android.util.log;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;/** * Created by Spring on 2015/11/7. * Download Tool class*/ Public classHttpdownloader {PrivateURL url =NULL; PrivateFinal String TAG ="TAG"; /** * Read text file * @param urlstr URL Path * @return text message * Download the file according to the URL, provided the content in this file is text, * 1. Create a URL Object * 2. Create an HTTP connection via the URL object * 3. Get InputStream * 4. Get data from InputStream*/ Publicstring Download (string urlstr) {StringBuffer sb=NewStringBuffer (); String Line=NULL; BufferedReader BufferedReader=NULL; Try{URL=NewURL (URLSTR); //Create an HTTP connectionHttpURLConnection Urlconn =(HttpURLConnection) url.openconnection (); //reading data using IO streamBufferedReader =NewBufferedReader (NewInputStreamReader (Urlconn.getinputstream ())); while(line = Bufferedreader.readline ())! =NULL) {sb.append (line); } } Catch(IOException e) {e.printstacktrace (); } finally { Try{bufferedreader.close (); } Catch(IOException e) {e.printstacktrace (); }} log.e ("TAG","Download TXT file"); LOG.E ("TAG", sb.tostring ()); returnsb.tostring (); } /** * Read Any file * return-1, on behalf of the download failed. Returns 0, which represents success. Returns 1 means the file already exists * * @param urlstr * @param path * @param fileName * @return*/ Public intdownlaodfile (String urlstr, String path, String fileName) {InputStream input=NULL; Try{fileutil Fileutil=NewFileutil (); if(Fileutil.isfileexist (Path +fileName)) { return 1; } Else{input=Getinputstearmformurl (URLSTR); File Resultfile=Fileutil.write2sdfrominput (path,filename,input); if(Resultfile = =NULL) return-1; } } Catch(IOException e) {e.printstacktrace (); return-1; } finally { Try{input.close (); } Catch(IOException e) {e.printstacktrace (); } } return 0; } PublicInputStream Getinputstearmformurl (String urlstr) throws IOException {URL=NewURL (URLSTR); HttpURLConnection Urlconn=(HttpURLConnection) url.openconnection (); InputStream input=Urlconn.getinputstream (); returninput; }}
Fileutil.java
Package Util;import Android.os.environment;import java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream;/** * Created by Spring on 2015/11/7.*/ Public classFileutil {PrivateString Sdpath; PublicFileutil () {} PublicString Getsdpath () {returnSdpath; } PublicFileutil (String sdpath) {//get a directory of external storage devices (/sdcard)Sdpath = environment.getexternalstoragedirectory () +"/" ; } /** * Create file on SD card * @param fileName * @return * @throws java.io.IOException*/ Publicfile Createsdfile (String fileName) throws IOException {file file=NewFile (Sdpath +fileName); File.createnewfile (); returnfile; } /** * Create directory on SD card * @param dirName directory name * @return file directory*/ Publicfile Createdir (String dirName) {file dir=NewFile (Sdpath +dirName); Dir.mkdir (); returndir; } /** * Determine if the file exists * @param fileName * @return*/ Publicboolean isfileexist (String fileName) {File file=NewFile (Sdpath +fileName); returnfile.exists (); } Publicfile Write2sdfrominput (String path,string filename,inputstream input) {file file=NULL; OutputStream Output=NULL; Try{createdir (path); File=createsdfile (path +fileName); Output=Newfileoutputstream (file); byte[] buffer =New byte[4*1024x768]; while(Input.read (buffer)! =-1) {output.write (buffer); Output.flush (); } } Catch(IOException e) {e.printstacktrace (); } finally { Try{output.close (); } Catch(IOException e) {e.printstacktrace (); } } returnfile; }}
3.MainActivity
Package Com.jingling.practice.downloadtest;import Android.app.activity;import android.os.bundle;import Android.view.view;import android.widget.button;import util. Httpdownloader; Public classMainactivity extends Activity {Httpdownloader downloader; PrivateButton Btn_downfile; PrivateButton Btn_downmp3; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Btn_downfile= (Button) This. Findviewbyid (R.id.button); Btn_downmp3= (Button) This. Findviewbyid (R.id.button2); Btn_downfile.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Downloader=NewHttpdownloader (); String Urlstr="Http://172.17.54.91:8080/download/down.txt"; Downloader.download (URLSTR); } }); Btn_downmp3.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {String urlstr="Http://172.17.54.91:8080/download/1.mp3"; String Path="file"; String FileName="2.mp3"; Httpdownloader Httpdownloader=NewHttpdownloader (); Httpdownloader.downlaodfile (Urlstr,path,filename); } }); }}
Android http download file and save to local or SD card