本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/除了可以在运行时去创建并使用文件,也可以在设计阶段把文件放在程序包中,这样一来就可以在运行时去使用他们。举个例子,你想把一些帮助文件打包进程序,当用户需要的时候,就可以展示给他们看。在这种情况下,应该把文件放在res/raw文件夹下面。
想要在代码中使用这个文件,需要调用Activity的getResources()方法,返回一个Resources对象。然后,使用它的openRawResource()方法去打开res/raw文件夹中的文件:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textBox = (EditText) findViewById(R.id.txtText1);
InputStream is = this.getResources().openRawResource(R.raw.textfile);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = null;
try {
while ((str = br.readLine()) != null) {
Toast.makeText(getBaseContext(),
str, Toast.LENGTH_SHORT).show();
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
注意,textfile.txt的id是R.raw.textfile