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

讀取 res/raw 資源檔:Android 原始資源存取實作

編輯:關於 Android 程式設計

若想把一份文字檔、音效或小型設定檔隨 App 一起打包,又不需要解析,res/raw 是最省事的位置。它不像 res/values 會被資源系統編譯改寫,檔案會原封不動地進入 APK,透過 Resources.openRawResource() 就能取得串流。

<?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/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="讀取資源文件(Raw)" />
    <TextView
        android:id="@+id/cont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
package com.example.yanlei.wifi;

import android.content.res.Resources;
import android.os.Bundle;
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.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {
    private Button btnRead = null;

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

        btnRead.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 取得資源物件
                Resources res = MainActivity.this.getResources();
                // 以 R.raw.friend 開啟 friend.txt,回傳 InputStream
                InputStream input = res.openRawResource(R.raw.friend);

                Scanner scan = new Scanner(input);
                StringBuffer info = new StringBuffer();
                while (scan.hasNext()) {
                    info.append(scan.next()).append("\n");
                }
                scan.close();
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext(), info.toString(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}

使用要點

把 friend.txt 放進 res/raw/ 即可,這個目錄預設並不存在,需要自行建立。raw 底下的檔名只能使用小寫字母、數字與底線,且不能以數字開頭,命名成 friend.txt 會自動對應到 R.raw.friend。

raw 與 assets 的差別值得記住:res/raw 的檔案會列進 R 類別、可直接用常數存取,但檔名受限且不能建子目錄;assets 則不進 R,需用 AssetManager.list() 遍歷,支援子資料夾,適合檔案眾多的情境。兩者都不會被壓縮儲存以外的處理,也不需要任何讀取權限,因為它們本來就屬於自己的 APK。

最後,串流務必關閉。範例中 Scanner 關閉後再關 InputStream 是安全的,但更簡潔的寫法是改用 try-with-resources,讓編譯器自動處理;若讀取的是較大的文字檔,建議改用 BufferedReader 逐行讀,避免一次載入造成記憶體峰值。

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