读取Resources和Assets中的文件
在Android系统中,我们可以对应用程序的私有文件夹中的文件进行操作之外,我们还可以从资源文件和Assets文件中获取数据,而这些文件分别存放在应用程序的res/raw和assets目录中,在编译时这些文件将同其他文件一起被打包。
另外,我们需要注意的就是来自Resources和Assets中的文件是只能读取而不能进行修改操作的。一般我们会在这些文件家中根据具体情况来存放项目的配置文件或其他类型的文件数据。
下面举例说明这两个文件中的文件操作。首先,我们需要在res/raw和assets文件中创建两个文件分别为file01.txt和file02.txt,并且为了防止读取的数据乱码,我们将这两个文件的格式编码设置为UTF-8编码,具体的操作实例代码如下:
Main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DataStoreRawAssetAct" >
<TextView
android:id="@+id/file01_val"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
<TextView
android:id="@+id/file02_val"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/file01_val"/>
</RelativeLayout>
DataStoreRawAssetAct.java:
package com.david.gl.datastorerawasset;
import java.io.InputStream;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class DataStoreRawAssetAct extends Activity {
private static final String ENCODING = "UTF-8";
TextView tv01;
TextView tv02;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv01 = (TextView) findViewById(R.id.file01_val);
tv01.setText(getFromRaw());
tv02 = (TextView) findViewById(R.id.file02_val);
tv02.setText(getFromAsset());
}
private String getFromRaw() {
String result = "";
try {
InputStream in = getResources().openRawResource(R.raw.file01);
int len = in.available();
byte[] buffer = new byte[len];
in.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
if (len == -1)
in.close();
}catch(Exception e) {
e.printStackTrace();
}
return result;
}
private String getFromAsset() {
String result = "";
try {
InputStream in = getResources().getAssets().open("file02.txt");
int len = in.available();
byte[] buffer = new byte[len];
in.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
if (len == -1)
in.close();
}catch(Exception e) {
e.printStackTrace();
}
return result;
}
}
代码如上,实例运行效果图如下:
如上图所示,上面一行的文字即是从res/raw中的file01.txt中读取的;而下面的文字则是从assets文件中的file02.txt中读取的。
在接下来的一片文章中介绍的是”简单数据的存储“---SharedPreferences的使用说明。敬请期待!!!
希望兴趣相投的同学来一起研究学习!群号是:179914858