Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 檔案下載與寫入 SD 卡完整實作

編輯:關於 Android 程式設計

從網路下載資源再存到裝置上,是幾乎每個 App 都會用到的能力。流程可以拆成兩半:先拿到資料流,再把資料流寫進檔案系統。以下把整個過程整理成可重複使用的工具類別。

一、檔案下載的三個步驟

步驟一:建立 HttpURLConnection。

// urlStr 指的是網路位址
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

步驟二:取得 InputStream。

InputStream input = null;
input = urlConn.getInputStream();

步驟三:加上網路權限。

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

另外,Android 4.0 之後主線程禁止網路連線,這整段流程必須放在背景線程(AsyncTask、Thread 或 Coroutine)裡執行。

二、SD 卡存取

手機內容量有限,大量資料通常得放進外部儲存。不同機型的掛載點並不一致,因此要用系統 API 取得路徑,而不是硬編碼:

// 取得目前裝置外部儲存裝置的目錄
Environment.getExternalStorageDirectory();

寫入前同樣要宣告權限(Android 6.0 起需執行期動態申請):

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

三、檔案工具類別

這個類別封裝了 SD 卡上最常做的幾件事,之後要操作檔案直接拿來用:

public class FileUtils {

    private String SDPATH;

    public String getSDPATH() {
        return SDPATH;
    }

    public FileUtils() {
        // 取得外部儲存裝置的目錄
        SDPATH = Environment.getExternalStorageDirectory() + "/";
    }

    /**
     * 在 SD 卡上建立檔案
     */
    public File creatSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }

    /**
     * 在 SD 卡上建立目錄
     */
    public File creatSDDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdirs();   // 用 mkdirs 才能一次建立多層
        return dir;
    }

    /**
     * 判斷檔案是否存在
     */
    public boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();
    }

    /**
     * 把 InputStream 的內容寫入 SD 卡
     */
    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];
            int len;
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}

這裡有兩處對原始範例的修正。一是 mkdir() 改為 mkdirs(),前者無法建立多層目錄,會導致下載到巢狀路徑時靜默失敗。二是寫入迴圈改為 write(buffer, 0, len),原本直接 write(buffer) 會把緩衝區尾端的殘留資料一起寫進檔案,讓下載的圖片或壓縮檔損毀。

四、下載工具類別

public class HttpDownloader {

    private URL url = null;
    private FileUtils fileUtils = new FileUtils();

    /**
     * @return 0 = 下載成功;1 = 檔案已存在;-1 = 下載失敗
     */
    public int downfile(String urlStr, String path, String fileName) {
        if (fileUtils.isFileExist(path + fileName)) {
            return 1;
        }

        InputStream input = null;
        try {
            input = getInputStream(urlStr);
            if (input == null) return -1;

            File resultFile = fileUtils.write2SDFromInput(path, fileName, input);
            return resultFile == null ? -1 : 0;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 取得 InputStream —— 所有檔案處理的前置動作,因此獨立成方法
     */
    public InputStream getInputStream(String urlStr) throws IOException {
        InputStream is = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(10000);
            urlConn.setReadTimeout(10000);
            is = urlConn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return is;
    }
}

相較於原始版本,這裡補上了 finally 關流與連線逾時設定。前者避免檔案描述符洩漏,後者則能防止網路異常時 App 無限期卡住。

五、Activity 中使用

public class MainActivity extends Activity {

    private Button downfile = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downfile = (Button) findViewById(R.id.downfile);
        downfile.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 實際專案請把下載放到背景線程
                HttpDownloader httpDownLoader = new HttpDownloader();
                int result = httpDownLoader.downfile(
                        "https://192.168.1.100:8080/test/file.jpg", "test/", "test.jpg");

                switch (result) {
                    case 0:
                        Toast.makeText(MainActivity.this, "下載成功!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "已有檔案!", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(MainActivity.this, "下載失敗!", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

一個讓人抓不著頭髮的坑

撰寫下載位址時千萬不要用 127.0.0.1 或 localhost。這個位址在手機上指向手機自己,而不是你的電腦。這個錯誤不會讓程式崩潰,它只會靜靜地下載失敗,然後你在 SD 卡裡翻半天找不到檔案——非常浪費時間。請改用電腦在區網中的實際 IP,並確認防火牆已放行該連接埠。

補充

本範例以「檔案是否已存在」作為唯一的重試判斷,實務上應該搭配 ETag 或 Content-Length 做續傳與完整性驗證。另外,Android 10 之後推出了 Scoped Storage,直接寫入任意路徑的做法已受限,新專案請改用 MediaStore 或 SAF(Storage Access Framework)。下載機制本身也建議交給 WorkManager 或 DownloadManager,它們能處理中斷續傳、佇列排程與通知提示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved