做遊戲不可能只靠內部儲存,總要讀外部的 SD 卡;但一切的起點,通常是先把打包在 APK 裡的資源讀出來。
assets/ 用來放應用需要的各類檔案,例如設定檔、音訊檔,它們會原封不動打包進應用。res/ 放的是各種資源,包含 icons、供國際化用的字串檔與介面配置的 XML,同樣會被打包,但由 Android 建置系統代管。
遊戲通常選 assets/,因為 res/ 對檔案的層級結構與命名有諸多限制,而 assets/ 可以任意建立多層子目錄,整理素材方便得多。
AssetManager assetManager = context.getAssets();
拿到管理器之後開啟檔案就一行的事:
InputStream inputStream = assetManager.open("dir/dir2/filename.txt");
這裡傳入的是相對於 assets 的路徑,也就是 Eclipse 裡的 assets/dir/dir2/filename.txt。回傳的是標準 Java InputStream,任何型別的檔案都能讀。
package org.example.ch04_android_basics;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;
public class AssetsTest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
setContentView(textView);
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try{
inputStream = assetManager.open("texts/myawesometext.txt");
String text = loadTextFile(inputStream);
textView.setText(text);
}catch(IOException e){
textView.setText("Couldn't load file");
}finally{
if(inputStream != null)
try{
inputStream.close();
}catch(IOException e){
textView.setText("Couldn't close file");
}
}
}
public String loadTextFile(InputStream inputStream) throws IOException{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int len = 0;
while((len = inputStream.read(bytes)) > 0)
byteStream.write(bytes, 0, len);
return new String(byteStream.toByteArray(), "UTF-8");
}
}
loadTextFile() 這個小方法用 4KB 緩衝區反覆讀取直到 read() 不再回傳正值,把位元組全部寫進 ByteArrayOutputStream,最後以 UTF-8 轉成字串。finally 中關流是必要收尾,assets 的檔案描述符數量有限,漏關久了會直接開不出新檔案。