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

Android 開發之路(十):內部儲存與 SD 卡的檔案讀寫實作

編輯:關於 Android 開發

Android 開發之路(十):檔案的讀寫

資料儲存的方式有好幾種,檔案是最基礎的一種。這一課分兩個部分:把資料寫進手機內部儲存空間,以及寫進 SD 卡。兩者的 API 相似,但權限與路徑取得方式不同,實作時要分清楚。

1. 存入手機內部儲存空間

① MainActivity.java

實作步驟:先建立布局檔(包含檔名與內容輸入框);在主 Activity 中取得控件並為按鈕掛上監聽器,負責讀取輸入內容並觸發儲存;由於業務邏輯通常放在 service 層,因此另外建立業務類別來完成寫入。

public class MainActivity extends Activity implements OnClickListener {

    private Button mButton;
    private EditText etFilename;
    private EditText etFileContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        etFilename = (EditText) findViewById(R.id.filename);
        etFileContent = (EditText) findViewById(R.id.filecontent);

        String filename = etFilename.getText().toString();
        String filecontent = etFileContent.getText().toString();

        FileService service = new FileService(getApplicationContext());
        try {
            service.save(filename, filecontent);
            Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}

② FileService.java

public class FileService {

    private Context context;

    public FileService(Context context) {
        this.context = context;
    }

    /** 儲存檔案到手機內部儲存 */
    public void save(String filename, String filecontent) throws Exception {
        /**
         * FileOutputStream:檔案輸出流
         * openFileOutput() 的參數:
         *   1. 要儲存的檔案名稱
         *   2. 儲存模式
         * 這裡使用 MODE_PRIVATE,代表產生的檔案只能被本應用存取,
         * 且寫入時會覆蓋原檔案的內容。
         */
        FileOutputStream outputStream =
                context.openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(filecontent.getBytes());
        outputStream.close();
    }

    /** 從手機內部儲存讀取檔案 */
    public String read(String filename) throws Exception {
        FileInputStream inputStream = context.openFileInput(filename);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        byte[] data = outputStream.toByteArray();
        return new String(data);
    }
}

除了 MODE_PRIVATE,另外兩個常用模式是 MODE_APPEND(追加而不覆蓋)與 MODE_WORLD_READABLE/MODE_WORLD_WRITEABLE(對外開放讀寫)。後兩者在 API 17 之後已被標記為危險並在後續版本停用,實務上不該再使用;需要對外分享檔案時,應改用 FileProvider。

③ 單元測試:FileServiceTest.java

public class FileServiceTest extends AndroidTestCase {

    private static final String TAG = "FileServiceTest";

    /** 測試 save() 方法是否有錯 */
    public void testSave() throws Throwable {
        FileService service = new FileService(this.getContext());
        service.save("456.txt", "sdfdgsdfasd");
        Log.i(TAG, "成功");
    }

    /** 測試 read() 方法是否有錯 */
    public void testRead() throws Throwable {
        FileService service = new FileService(this.getContext());
        String result = service.read("123.txt");
        Log.i(TAG, result);
    }
}

④ 清單檔 AndroidManifest.xml

要執行單元測試,必須在清單檔中加上 instrumentation 標籤與 uses-library:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.rookie.test1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="10" />

    <!-- 指定單元測試的唯一標識 -->
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.rookie.test1"
        android:label="testapp"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <!-- 加入單元測試環境 -->
        <uses-library android:name="android.test.runner" />

        <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>

⑤ 布局檔 activity_main.xml(此處省略)

2. 存入 SD 卡

要寫入 SD 卡,必須先在清單檔中宣告相關權限:

<!-- 在 sd 卡中建立與刪存檔案的權限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往 sd 卡寫入資料的權限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

接著在 FileService.java 中新增一個方法:

/** 儲存檔案到 sdcard */
public void saveToSDCard(String filename, String filecontent) throws Exception {
    File file = new File(Environment.getExternalStorageDirectory(), filename);
    FileOutputStream outputStream = new FileOutputStream(file);
    outputStream.write(filecontent.getBytes());
    outputStream.close();
}

然後把 MainActivity 中原本改寫過的 onClick() 改成:

@Override
public void onClick(View v) {
    etFilename = (EditText) findViewById(R.id.filename);
    etFileContent = (EditText) findViewById(R.id.filecontent);

    String filename = etFilename.getText().toString();
    String filecontent = etFileContent.getText().toString();

    FileService service = new FileService(getApplicationContext());
    try {
        // 先判斷 sd 卡是否存在且可讀寫
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            service.saveToSDCard(filename, filecontent);
            Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), R.string.sd_error, Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

到這裡,寫入 SD 卡的功能就完成了,跑一下試試看。

幾個實務上會踩到的補充

  • 內部儲存與外部儲存的命名很反直覺:Android 把 openFileOutput() 存的那片空間叫「內部儲存」,而把一般使用者認知的 SD 卡叫「外部儲存」。兩者都不需要 SD 卡權限前者需要,後者需要 WRITE_EXTERNAL_STORAGE。
  • Android 6.0 之後權限要動態申請:寫入外部儲存屬於危險權限,除了在清單檔宣告,還必須在執行期用 requestPermissions() 向使用者取得同意,否則會直接收到 SecurityException。
  • 寫檔要放子執行緒:檔案 I/O 屬於耗時操作,放在主執行緒會觸發 StrictMode 警告,也可能造成畫面卡頓。
  • 用 try-with-resources 確保關流:例外發生時,未關閉的串流會造成資源洩漏,Java 7 之後可直接用 try (FileOutputStream os = ...) 自動關閉。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved