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

把資料寫進 SD 卡:Android 外部儲存的讀寫實作

編輯:關於 Android 程式設計

內部儲存空間在 App 移除時會一併清除,若要放使用者產生的檔案或較大的資料,寫到外部儲存(SD 卡)是常見選擇。以下示範兩個按鈕,一個負責寫入、一個負責讀回,並把外部儲存的判斷與權限處理完整交代。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存數據(File)" />
    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="讀取數據(File)" />
</LinearLayout>
package com.example.yanlei.wifi;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {
    private Button btnSave = null;
    private Button btnRead = null;
    private File file = null;
    private static final String FILENAME = "data.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSave = (Button) super.findViewById(R.id.save);
        btnRead = (Button) super.findViewById(R.id.read);

        btnSave.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 寫入前務必先確認外部儲存已掛載
                if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!",
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String path = Environment.getExternalStorageDirectory().toString()
                        + File.separator + "genwoxue" + File.separator + FILENAME;
                file = new File(path);
                // 父目錄不存在時先建立
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }

                PrintStream ps = null;
                try {
                    ps = new PrintStream(new FileOutputStream(file));
                    ps.println("跟我學網址:www.genwoxue.com");
                    ps.println("");
                    ps.println("電子郵件:hello@genwoxue.com");
                    Toast.makeText(getApplicationContext(), "保存成功!", Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (ps != null) {
                        ps.close();
                    }
                }
            }
        });

        btnRead.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!",
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String path = Environment.getExternalStorageDirectory().toString()
                        + File.separator + "genwoxue" + File.separator + FILENAME;
                file = new File(path);
                if (!file.exists()) {
                    Toast.makeText(getApplicationContext(), "文件不存在!", Toast.LENGTH_LONG).show();
                    return;
                }

                StringBuffer info = new StringBuffer();
                Scanner scan = null;
                try {
                    scan = new Scanner(new FileInputStream(file));
                    while (scan.hasNext()) {
                        info.append(scan.next()).append("☆☆☆\n");
                    }
                    Toast.makeText(getApplicationContext(), info.toString(),
                            Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (scan != null) {
                        scan.close();
                    }
                }
            }
        });
    }
}

權限宣告

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.yanlei.wifi" >

    <!-- 在 SDCard 中創建與刪除文件 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 讀取外部儲存 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <!-- 寫入外部儲存 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

三個必讀的實務提醒

第一,WRITE_EXTERNAL_STORAGE 屬於危險權限,Android 6.0 起僅在 Manifest 宣告不夠,必須在執行期用 requestPermissions 向使用者動態詢問,否則 getExternalStorageDirectory 寫入會直接抛出 SecurityException。

第二,Android 4.4 之後,即使拿到寫入權限,App 也只能在外部儲存中屬於自己的目錄(getExternalFilesDir())自由寫入,對其他目錄的寫入受限。跨版本都安全的做法是改用 getExternalFilesDir(),免權限且不受系統清理策略影響。

第三,範例中的檔案 I/O 寫在主執行緒上,資料量一大就會造成 ANR,實務上請移到背景執行緒,並在 finally 中確保串流關閉。另外 MOUNT_UNMOUNT_FILESYSTEMS 是系統保留權限,一般應用無法取得,可以從宣告中移除。

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