1. 程式人生 > >檔案下載類 HttpDownloader,記憶體卡操作類 FileUtils

檔案下載類 HttpDownloader,記憶體卡操作類 FileUtils

download.java

package zlj.download;

import zlj.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 Download extends Activity {
    /** Called when the activity is first created. */
    private Button downloadText = null;
    private Button downloadMp3 = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        downloadText = (Button)findViewById(R.id.downloadText);
        downloadText.setOnClickListener(new downloadTextClicklistener());
        downloadMp3 = (Button)findViewById(R.id.downloadMp3);
        downloadMp3.setOnClickListener(new downloadMp3Clicklistener());
    }
    class downloadTextClicklistener implements OnClickListener{

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            HttpDownloader httpDownloader = new HttpDownloader();
            //http://www.lrc123.com/download/lrc/86547-30.aspx ,流星
            System.out.println("開始下載文字");
            String lrc = httpDownloader.download("http://115.156.228.135:8080/Mp3/liuxing.lrc");//localhost手機無法識別
        //    String lrc1 = httpDownloader.download("http://www.lrc123.com/download/lrc/86547-30.aspx");
            System.out.println("lrc->" + lrc);
        //    System.out.println("lrc1->" + lrc1);
        }
        
    }
    class downloadMp3Clicklistener implements OnClickListener{

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            HttpDownloader httpDownloader = new HttpDownloader();
            System.out.println("開始下載Mp3");
            int result = httpDownloader.downloadFile("http://115.156.228.135:8080/Mp3/liuxing.mp3","Mp3/","liuxing.mp3");
            System.out.println(result);
        }
        
    }
}

HttpDownloader.java

複製程式碼
 1 package mars.utils;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.File;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.InputStreamReader;
 8 import java.net.HttpURLConnection;
 9 import java.net.MalformedURLException;
10 import java.net.URL;
11 12 13 public class HttpDownloader { 14 private URL url = null; 15 16 /** 17 * 根據URL下載檔案,前提是這個檔案當中的內容是文字,函式的返回值就是檔案當中的內容 18 * 1.建立一個URL物件 19 * 2.通過URL物件,建立一個HttpURLConnection物件 20 * 3.得到InputStram 21 * 4.從InputStream當中讀取資料 22 * @param urlStr 23 * @return 24 */ 25 public String download(String urlStr) { 26 StringBuffer sb = new StringBuffer(); 27 String line = null; 28 BufferedReader buffer = null; 29 try { 30 // 建立一個URL物件 31 url = new URL(urlStr); 32 // 建立一個Http連線 33 HttpURLConnection urlConn = (HttpURLConnection) url 34 .openConnection(); 35 // 使用IO流讀取資料 36 buffer = new BufferedReader(new InputStreamReader(urlConn 37 .getInputStream())); 38 while ((line = buffer.readLine()) != null) { 39 sb.append(line); 40 } 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } finally { 44 try { 45 buffer.close(); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 } 50 return sb.toString(); 51 } 52 53 /** 54 * 該函式返回整形 -1:代表下載檔案出錯 0:代表下載檔案成功 1:代表檔案已經存在 55 */ 56 public int downloadFile(String urlStr, String path, String fileName) {//Mark,下載檔案 57 InputStream inputStream = null; 58 try { 59 FileUtils fileUtils = new FileUtils(); 60 61 if (fileUtils.isFileExist(path + fileName)) { 62 return 1; 63 } else { 64 inputStream = getInputStreamFromUrl(urlStr); 65 File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream); 66 if (resultFile == null) { 67 return -1; 68 } 69 } 70 } catch (Exception e) { 71 e.printStackTrace(); 72 return -1; 73 } finally { 74 try { 75 inputStream.close(); 76 } catch (Exception e) { 77 e.printStackTrace(); 78 } 79 } 80 return 0; 81 } 82 83 /** 84 * 根據URL得到輸入流 85 * 86 * @param urlStr 87 * @return 88 * @throws MalformedURLException 89 * @throws IOException 90 */ 91 public InputStream getInputStreamFromUrl(String urlStr) 92 throws MalformedURLException, IOException { 93 url = new URL(urlStr); 94 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 95 InputStream inputStream = urlConn.getInputStream(); 96 return inputStream; 97 } 98 }
複製程式碼



FileUtils.java

複製程式碼
 1 package mars.utils;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 
 9 import android.os.Environment;
10 
11 public class FileUtils {
12     private String SDPATH;
13 
14     public String getSDPATH() {
15         return SDPATH;
16     }
17     public FileUtils() {
18         //得到當前外部儲存裝置的目錄
19         // /SDCARD
20         SDPATH = Environment.getExternalStorageDirectory() + "/";
21     }
22     /**
23      * 在SD卡上建立檔案
24      * 
25      * @throws IOException
26      */
27     public File creatSDFile(String fileName) throws IOException {
28         File file = new File(SDPATH + fileName);
29         file.createNewFile();
30         return file;
31     }
32     
33     /**
34      * 在SD卡上建立目錄
35      * 
36      * @param dirName
37      */
38     public File creatSDDir(String dirName) {
39         File dir = new File(SDPATH + dirName);
40         dir.mkdirs();
41         return dir;
42     }
43 
44     /**
45      * 判斷SD卡上的資料夾是否存在
46      */
47     public boolean isFileExist(String fileName){
48         File file = new File(SDPATH + fileName);
49         return file.exists();
50     }
51     
52     /**
53      * 將一個InputStream裡面的資料寫入到SD卡中
54      */
55     public File write2SDFromInput(String path,String fileName,InputStream input){
56         File file = null;
57         OutputStream output = null;
58         try{
59             creatSDDir(path);
60             file = creatSDFile(path + fileName);
61             output = new FileOutputStream(file);
62             byte buffer [] = new byte[4 * 1024];
63             while((input.read(buffer)) != -1){
64                 output.write(buffer);
65             }
66             output.flush();
67         }
68         catch(Exception e){
69             e.printStackTrace();
70         }
71         finally{
72             try{
73                 output.close();
74             }
75             catch(Exception e){
76                 e.printStackTrace();
77             }
78         }
79         return file;
80     }
81 
82 }
複製程式碼

main.xml

<?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="@string/hello"
    />
    <Button
     android:id="@+id/downloadText"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="下載文字"
     />
     <Button
     android:id="@+id/downloadMp3"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="下載Mp3"
     />
     
    
</LinearLayout>


AndroidManifest.xml

複製程式碼
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3       package="mars.download"
 4       android:versionCode="1"
 5       android:versionName="1.0">
 6     <application android:icon="@drawable/icon" android:label="@string/app_name">
 7         <activity android:name=".Download"
 8                   android:label="@string/app_name">
 9             <intent-filter>
10                 <action android:name="android.intent.action.MAIN" />
11                 <category android:name="android.intent.category.LAUNCHER" />
12             </intent-filter>
13         </activity>
14     </application>
15     <uses-sdk android:minSdkVersion="4" />
16     <uses-permission android:name="android.permission.INTERNET"/>
17     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
18 </manifest> 
複製程式碼