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

Android 檔案操作三件事:建資料夾、寫檔案、安裝 APK

編輯:關於 Android 程式設計

這三個動作在 Android 上都是幾行的事,但每次要用的時候總會忘記細節,所以整理成一份備忘。

一、建立資料夾

File sd = Environment.getExternalStorageDirectory();
String path = sd.getPath() + "/notes";
File file = new File(path);
if (!file.exists()) file.mkdir();

要一次建多層目錄的話,把 mkdir() 換成 mkdirs()。另外建議把路徑改成 Environment.getExternalFilesDir() 或 getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),前者是應用專屬目錄、不需要任何權限,後者才是真正對外的公共位置。

二、建立並寫入檔案

示範從網路抓一張圖存成本機檔案:

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://img3.3lian.com/2006/016/09/031.jpg");
HttpResponse httpResponse = httpClient.execute(httpGet);

if (httpResponse.getStatusLine().getStatusCode() == 200) {
    total_length = httpResponse.getEntity().getContentLength();
    is = httpResponse.getEntity().getContent();

    File file = new File(Environment.getExternalStorageDirectory(), "aupdata.jpg");
    fos = new FileOutputStream(file);
    bis = new BufferedInputStream(is);

    byte[] buffer = new byte[1024];
    byte[] result_two = new byte[(int) total_length];
    int len = 0;
    int total = 0;

    while ((len = bis.read(buffer)) > -1) {
        System.arraycopy(buffer, 0, result_two, total, len);
        fos.write(buffer, 0, len);
        total = total + len;
    }
}

重點就一句:FileOutputStream 建立檔案,write() 寫入內容,檔案就產生了。

不過要說清楚,這段寫法有幾個該避免的地方:DefaultHttpClient 早已廢棄,result_two 這個陣列其實完全沒被用到,而網路請求寫在主線程會直接觸發 NetworkOnMainThreadException。現代寫法應該用 HttpURLConnection 或 OkHttp,搭配協程/背景執行緒,串流直接從輸入流拷貝到輸出流即可,不必先把整個檔案讀進記憶體。

三、安裝其他 APK

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File install_file = new File(Environment.getExternalStorageDirectory(), "MyWeb.apk");
intent.setDataAndType(Uri.fromFile(install_file), "application/vnd.android.package-archive");
startActivity(intent);

這段在 Android 4.x 時代可以正常運作,但在新版本上會遇到兩道關卡:

  • Android 7.0 起禁止 file:// URI 跨應用傳遞,會拋 FileUriExposedException。必須改用 FileProvider 取得 content:// URI,並在 Manifest 宣告對應的 provider 與 paths。
  • 還需要在 Manifest 加上 REQUEST_INSTALL_PACKAGES 權限,並引導使用者到系統設定手動允許「安裝未知應用」。

改用 FileProvider 之後,記得補上 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION),否則目標應用讀不到檔案。

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