Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android _文件下載

Android _文件下載

編輯:關於Android編程

   Android 文件下載,在Android開發中很長用到,經常需要在應用程序中下載所需要的文件比如電子書,MP3格式的音樂文件,電影等。我在這裡總結了一下,以後要用時可以直接拷貝,

代碼分析:

  有兩個工具類,HttpDownloader.java類中定義兩個下載方法,download(String urlstr)下載純文本文件,downfile(String urlStr,String path,String fileName)下載字節文件類。FileUtils.java類定義了寫入sd卡的操作。Download.java類為主線程類,兩個按鈕,監聽下載事件。

注意:


     在AndroidManifest.xml中添加網絡訪問權限

           <uses-permission android:name="android.permission.INTERNET"/> 

     在AndroidManifest.xml中加入訪問SDCard的權限

           <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

代碼:

   main.xml


[java] <?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="Android_hello word" 
    /> 
<Button 
    android:id="@+id/buttontxt" 
    android:layout_width="300dp" 
    android:layout_height="wrap_content" 
    android:text="單擊下載txt文件" 
    /> 
<Button 
    android:id="@+id/buttonmp3" 
    android:layout_width="300dp" 
    android:layout_height="wrap_content" 
    android:text="單擊下載mp3文件" 
    /> 
</LinearLayout> 

<?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="Android_hello word"
    />
<Button
 android:id="@+id/buttontxt"
 android:layout_width="300dp"
 android:layout_height="wrap_content"
 android:text="單擊下載txt文件"
 />
<Button
 android:id="@+id/buttonmp3"
 android:layout_width="300dp"
 android:layout_height="wrap_content"
 android:text="單擊下載mp3文件"
 />
</LinearLayout>
  Download.java

 

[java]  package com.example.download; 
 
import android.os.Bundle; 
import android.app.Activity; 
 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
 
public class Download extends Activity { 
    private Button buttontxt; 
    private Button buttonmp3; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_download); 
        buttontxt = (Button) findViewById(R.id.buttontxt); 
        buttontxt.setOnClickListener(new OnClickListener() { 
 
            public void onClick(View v) { 
                // TODO Auto-generated method stub  
                // TODO Auto-generated method stub  
                // 創建一個匿名線程用於下載文件  
                new Thread() { 
                    public void run() { 
                        HttpDownloader httpDownloader = new HttpDownloader(); 
                        // 調用httpDownloader對象的重載方法download下載txt文件  
                        String txt = httpDownloader 
                                .download("http://www.baidu.com/"); 
                        System.out.println(txt); 
                    } 
                }.start(); 
            } 
 
        }); 
 
        buttonmp3 = (Button) findViewById(R.id.buttonmp3); 
        // 為buttonmp3添加單擊事件監聽器  
        buttonmp3.setOnClickListener(new OnClickListener() { 
 
            /*
             * (non-Javadoc)
             * 
             * @see android.view.View.OnClickListener#onClick(android.view.View)
             */ 
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub  
                new Thread() { 
                    public void run() { 
                        try { 
                            HttpDownloader httpDownloader = new HttpDownloader(); 
                            // 調用httpDownloader對象的重載方法download下載mp3文件  
                            int result = httpDownloader 
                                    .downfile( 
                                            "http://sjrjy.apkzz.net/201011/291354164ea84578066309.jpg", 
                                            "Android/", "9.jpg"); 
                            System.out.println(result); 
                        } catch (Exception e) { 
                            e.printStackTrace(); 
                        } 
                    } 
                }.start(); 
 
            } 
        }); 
    } 
 

package com.example.download;

import android.os.Bundle;
import android.app.Activity;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Download extends Activity {
 private Button buttontxt;
 private Button buttonmp3;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_download);
  buttontxt = (Button) findViewById(R.id.buttontxt);
  buttontxt.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    // 創建一個匿名線程用於下載文件
    new Thread() {
     public void run() {
      HttpDownloader httpDownloader = new HttpDownloader();
      // 調用httpDownloader對象的重載方法download下載txt文件
      String txt = httpDownloader
        .download("http://www.baidu.com/");
      System.out.println(txt);
     }
    }.start();
   }

  });

  buttonmp3 = (Button) findViewById(R.id.buttonmp3);
  // 為buttonmp3添加單擊事件監聽器
  buttonmp3.setOnClickListener(new OnClickListener() {

   /*
    * (non-Javadoc)
    *
    * @see android.view.View.OnClickListener#onClick(android.view.View)
    */
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    new Thread() {
     public void run() {
      try {
       HttpDownloader httpDownloader = new HttpDownloader();
       // 調用httpDownloader對象的重載方法download下載mp3文件
       int result = httpDownloader
         .downfile(
           "http://sjrjy.apkzz.net/201011/291354164ea84578066309.jpg",
           "Android/", "9.jpg");
       System.out.println(result);
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
    }.start();

   }
  });
 }

}

  HttpDownloader.java

 

[java]  package com.example.download; 
 
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 bufferedReader=null; 
      try { 
        //創建一個URL對象  
        url=new URL(urlstr); 
        //得到一個HttpURLConnection對象  
        HttpURLConnection httpsURLConnection=(HttpURLConnection) url.openConnection(); 
        // 得到IO流,使用IO流讀取數據   
        bufferedReader=new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream())); 
        while((line=bufferedReader.readLine())!=null){//一行一行的讀  
            stringBuffer.append(line); 
        } 
             
    } catch (Exception e) { 
        e.printStackTrace(); 
    }  
    return stringBuffer.toString(); 
       
  } 
 
  // 該函數返回整形 -1:代表下載文件出錯 ;0:代表下載文件成功; 1:代表文件已經存在   
 public int downfile(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) {   
             e.printStackTrace();   
         }   
         File file=fileUtils.writeToSDPATHFromInput(path, fileName, inputstream);   
         if(file!=null)   
             return 0;   
         else    
             return -1;   
     }   
      
      
 
      
 } 
//根據url字符串得到輸入流    
public InputStream getFromUrl(String urlStr) throws IOException   
{          
    url=new URL(urlStr);               
    HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection();   
    InputStream input=httpUrlConnection.getInputStream();      
    return input;   
}   
}  

package com.example.download;

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 bufferedReader=null;
   try {
  //創建一個URL對象
  url=new URL(urlstr);
  //得到一個HttpURLConnection對象
  HttpURLConnection httpsURLConnection=(HttpURLConnection) url.openConnection();
  // 得到IO流,使用IO流讀取數據
  bufferedReader=new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
  while((line=bufferedReader.readLine())!=null){//一行一行的讀
   stringBuffer.append(line);
  }
   
 } catch (Exception e) {
  e.printStackTrace();
 }
 return stringBuffer.toString();
  
  }

  // 該函數返回整形 -1:代表下載文件出錯 ;0:代表下載文件成功; 1:代表文件已經存在
 public int downfile(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) { 
             e.printStackTrace(); 
         } 
         File file=fileUtils.writeToSDPATHFromInput(path, fileName, inputstream); 
         if(file!=null) 
             return 0; 
         else  
             return -1; 
     } 
 
 

 
 }
//根據url字符串得到輸入流 
public InputStream getFromUrl(String urlStr) throws IOException 
{        
    url=new URL(urlStr);             
    HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection(); 
    InputStream input=httpUrlConnection.getInputStream();    
    return input; 

}


  FileUtils.java


[java]  package com.example.download; 
 
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() { 
        // 獲得當前外部存儲設備SD卡的目錄  
        SDPATH = Environment.getExternalStorageDirectory() + "/"; 
    } 
 
    // 創建文件  
    public File createFile(String fileName) throws IOException { 
        File file = new File(SDPATH + fileName); 
        file.createNewFile(); 
        return file; 
    } 
 
    // 創建目錄  
    public File createDir(String fileName) throws IOException { 
        File dir = new File(SDPATH + fileName); 
        dir.mkdir(); 
        return dir; 
    } 
 
    // 判斷文件是否存在  
    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 outputstream = null; 
        try { 
            createDir(path); 
            file = createFile(path + fileName); 
            outputstream = new FileOutputStream(file); 
            byte buffer[] = new byte[1024]; 
            // 將輸入流中的內容先輸入到buffer中緩存,然後用輸出流寫到文件中, /*真機測試,這段可能有問題  
            /*while ((inputstream.read(buffer)) != -1) { 
                outputstream.write(buffer); 
            }*/ 
            //用這段  
            int length; 
            while((length=(inputstream.read(buffer))) >0){ 
            outputstream.write(buffer,0,length); 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                inputstream.close(); 
                outputstream.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
        return file; 
    } 
 

package com.example.download;

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() {
  // 獲得當前外部存儲設備SD卡的目錄
  SDPATH = Environment.getExternalStorageDirectory() + "/";
 }

 // 創建文件
 public File createFile(String fileName) throws IOException {
  File file = new File(SDPATH + fileName);
  file.createNewFile();
  return file;
 }

 // 創建目錄
 public File createDir(String fileName) throws IOException {
  File dir = new File(SDPATH + fileName);
  dir.mkdir();
  return dir;
 }

 // 判斷文件是否存在
 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 outputstream = null;
  try {
   createDir(path);
   file = createFile(path + fileName);
   outputstream = new FileOutputStream(file);
   byte buffer[] = new byte[1024];
   // 將輸入流中的內容先輸入到buffer中緩存,然後用輸出流寫到文件中, /*真機測試,這段可能有問題
   /*while ((inputstream.read(buffer)) != -1) {
    outputstream.write(buffer);
   }*/
   //用這段
   int length;
   while((length=(inputstream.read(buffer))) >0){
   outputstream.write(buffer,0,length);
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    inputstream.close();
    outputstream.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return file;
 }

}

 

 


[java]

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved