Android _ file download, android File Download

Source: Internet
Author: User

Android _ file download, android File Download

Android downloads files from the network

Steps:

1. Use HTTP to download files

-Create an HttpURLConnection object: HttpURLConnection urlConn = (HttpURLConnection) url. openConnection ();

-Get an InputStream object: urlConn. getInputStream ()

-Network access permission: android. permission. INTERNET

2. Write the downloaded file to SDCARD

-Get the directory of the SD card of the current device: Environment. getExternalStrageDirectory ()

-Permission to access the SD card: android. permission. WRITE_EXTERNAL_STORAGE

Code:

Activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <Button        android:id="@+id/btn_txt"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="download lrc" />        <Button        android:id="@+id/btn_mp3"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/btn_txt"        android:text="download mp3" /></RelativeLayout>
MainActivity. java
Package com. chay. download; import com. chay. 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 MainActivity extends Activity {String urlStr_txt = "http: // 192.168.56.1: 8080/mp3/wan. lrc "; String urlStr_mp3 =" http: // 192.168.56.1: 8080/mp3/wan.mp3 "; String path =" mp3/"; String fileName =" wanw."; private Button downloadTxtButton; private Button downloadMp3Button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); downloadTxtButton = (Button) findViewById (R. id. btn_txt); downloadTxtButton. setOnClickListener (new DownloadTxtListener (); downloadMp3Button = (Button) findViewById (R. id. btn_mp3); downloadMp3Button. setOnClickListener (new DownloadMp3Listener ();} // listener class DownloadTxtListener implements OnClickListener {@ Overridepublic void onClick (View v) {Thread t = new DownloadTxtThread (); t. start (); System. out. println ("txt --->") ;}// download the lyrics file Thread class DownloadTxtThread extends Thread {@ Overridepublic void run () {HttpDownloader httpDownloader = new HttpDownloader (); string lrc = httpDownloader. download (urlStr_txt); System. out. println (lrc) ;}/// listener class DownloadMp3Listener implements OnClickListener {@ Overridepublic void onClick (View v) {Thread h = new DownMp3Thread (); h. start (); System. out. println ("mp3 --->") ;}// download MP3 file Thread class DownMp3Thread extends Thread {@ Overridepublic void run () {HttpDownloader httpDownloader = new HttpDownloader (); int result = httpDownloader. downFile (urlStr_mp3, path, fileName); System. out. println (result );}}}
Tool class:
HttpDownloader. java
Package com. chay. 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 URL = null;/*** download an object based on the URL, provided that the content of the object is text, 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. read data from InputStream * @ param urlStr * @ return */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 (); // read data buffer = new BufferedReader (new InputStreamReader (urlConn. getInputStream () ); 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 ();}/*** this function returns an integer-1: indicates that the object is downloaded. error 0: indicates that the object is successfully downloaded. 1: indicates that the file already exists */public int downFile (String urlStr, String path, String fileName) {InputStream inputStream = null; try {FileUtils 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 ** @ param urlStr * @ return * @ throws MalformedURLException * @ throws IOException */public InputStream getInputStreamFromUrl (String urlStr) throws MalformedURLException, IOException {url = new URL (urlStr); HttpURLConnection urlConn = (HttpURLConnection) url. openConnection (); InputStream inputStream = urlConn. getInputStream (); return inputStream ;}}
FileUtils. java
Package com. chay. 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; public class FileUtils {private String SDPATH; public String getSDPATH () {return SDPATH;} public FileUtils () {// obtain the directory of the current external storage device // SDCARDSDPATH = Environment. getExternalStorageDirectory () + "/";}/*** create a file on the SD card ** @ th Rows IOException */public File creatSDFile (String fileName) throws IOException {File file File = new file (SDPATH + fileName); File. createNewFile (); return file;}/*** create a directory on the SD card ** @ param dirName */public File creatSDDir (String dirName) {File dir = new File (SDPATH + dirName); dir. mkdirs (); return dir;}/*** determines whether the folder on the SD card exists */public boolean isFileExist (String fileName) {File 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 file = null; outputStream output = null; try {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 ;}}
---------------------------------------------------------------------------------




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.