1. 程式人生 > >Android 下載伺服器檔案 httpurl

Android 下載伺服器檔案 httpurl

文章目錄

1、簡介

下載網路伺服器上的檔案

2、檔案結構

在這裡插入圖片描述

3、AndroidMainfest 新增許可權

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

4、MainActivity 實現

package com.example.tssh.mydownloadfile;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private String  TAG = "MainActivity: ";

    private String  urlLoadPath = "http://dl.kkdownload.com/kz2sem2/KuaiZip_Setup_sem2_604.exe";  //下載的檔案 網路地址
    private String savaDirPath = "testLoad";  //儲存的地址
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //先去檢查有沒有相應許可權
        CheckThread checkThread  = new CheckThread();
        checkThread.start();
        try {
            checkThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                DownLoadFileFormUrl(urlLoadPath,savaDirPath); //呼叫下載函式
            }
        }).start();

    }


    public boolean DownLoadFileFormUrl(String urlLoadPath, String savaDirPath){
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        HttpURLConnection httpURLConnection = null;

        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Log.i(TAG," 未安裝 SD 卡");
            return  false;
        }
        File pathSd = Environment.getExternalStorageDirectory();  //獲取 SD 卡路徑
        File fileRealDirectoty  = new File(pathSd.getAbsolutePath() + File.separator + savaDirPath);
        Log.i(TAG,"檔案儲存的真正目錄: " + fileRealDirectoty);
        if (!fileRealDirectoty.exists()) {  //如果目錄 不存在 ,就建立
            Log.i(TAG,"建立 儲存資料夾");
            fileRealDirectoty.mkdirs();
        }
        //獲取要下載的檔名稱,在這裡可以更改下載的檔名
        String fileName = urlLoadPath.substring(urlLoadPath.lastIndexOf("/") + 1);
        //String fileName = "test.zip";
        //建立 這個檔名 命名的 file 物件
        File file = new File(fileRealDirectoty,fileName);
        Log.i(TAG,"file: " + file);
        if (!file.exists()) {  //倘若沒有這個檔案
            try {
                Log.i(TAG,"建立檔案");
                file.createNewFile();  //建立這個檔案
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            URL url = new URL(urlLoadPath);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            //根據響應獲取檔案大小
            int fileSize = httpURLConnection.getContentLength();
            Log.i(TAG,"檔案大小: " + fileSize);
            inputStream = httpURLConnection.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int tem = 0;
            while ((tem = inputStream.read(b))!= -1) {
                fileOutputStream.write(b,0,tem);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }

                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.i(TAG,"檔案下載 成功");
        return true;
    }



    //sd 卡許可權申請
    private void checkPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if(requestCode == 100){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "");

            }
        }
    }

    public  class CheckThread  extends  Thread{
        public void run() {
           checkPermission();
        }
    }
}

5、效果顯示

在這裡插入圖片描述

檔案參考:
《Android 典型技術模組開發詳解》

本人鄭重宣告,本部落格所編文章、圖片版權歸權利人持有,本博只做學習交流分享所用,不做任何商業用途。訪問者可將本博提供的內容或服務用於個人學習、研究或欣賞,不得用於商業使用。同時,訪問者應遵守著作權法及其他相關法律的規定,不得侵犯相關權利人的合法權利;如果用於商業用途,須徵得相關權利人的書面授權。若文章、圖片的原作者不願意在此展示內容,請及時通知在下,將及時予以刪除。