提纲:
一:assets目录介绍
二:assets目录下文件的读取
1.读取readme。txt文件的内容
2.读取文件名
3.转移assets的一个db文件到数据库
一:assets目录介绍
Android 系统为每个新设计的程序提供了/assets目录,这个目录保存的文件可以打包在程序里。/res 和/assets的不同点是,android不为/assets下的文件生成ID。如果使用/assets下的文件,需要指定文件的路径和文件名。
二:assets目录下文件的读取
1.读取readme。txt文件的内容
AssetManager assetManager = this.getAssets();
AssetInputStream is = null;
try {
//通过文件名获取数据流,txt文件数据要为UTF-8类型,否则会出现乱码,可在eclipse
//里通过修改文件属性更改
is = (AssetInputStream) assetManager.open("readme.txt");
} catch (IOException e) {
e.printStackTrace();
}
//将输入流读取的内容转为String类型
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
try {
while((len =is.read(buffer))!=-1){
out.write(buffer, 0, len);
}
out.close();
is.close();
} catch (IOException e) {
}
tv1.setText(out.toString());
2.读取文件名
String[] fileName = null;
try {
fileName = assetManager.list("image");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv2.setText(fileName[0]+", "+ fileName[1]);
3.转移assets的一个db文件到数据库
String targetFileName = "/data/data/"+this.getPackageName()+"/databases/base.db";
copyFileForAssrts(this, "base.db", targetFileName);
SQLiteDatabase db = openOrCreateDatabase("base.db", 0, null);
Cursor cursor = db.rawQuery("select area_id from geo where name_cn =?", new String[]{"武汉"});
String area_id = null;
while(cursor.moveToNext()){
area_id = cursor.getString(cursor.getColumnIndex("area_id"));
}
tv3.setText("获取天气的武汉区域id:"+area_id);
private void copyFileForAssrts(Context context,String assetsFileName, String targetFileName){
FileOutputStream outStream = null;
AssetInputStream is = null;
try {
File file = new File(targetFileName);
if(file.exists())
file.delete();
createMultPath(file.getParentFile().getAbsolutePath());
file.createNewFile();
outStream = new FileOutputStream(file);
is = (AssetInputStream) context.getAssets().open(assetsFileName);
byte[] buffer = new byte[1024];
int len = -1;
while((len = is.read(buffer))!=-1){
outStream.write(buffer, 0, len);
}
outStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
is.close();
outStream.close();
} catch (IOException e) {
}
}
}
// 创建目录
public static void createMultPath(String path) {
StringTokenizer st = new StringTokenizer(path, "/");
String path1 = st.nextToken() + "/";
String path2 = path1;
while (st.hasMoreTokens()) {
path1 = st.nextToken() + "/";
path2 += path1;
File inbox = new File(path2);
if (!inbox.exists())
inbox.mkdir();
}
}
对于assets目录下的文件,知道第1个方法就够了,因为这些文件名你肯定知道,然后在通过流来转换成不同形式显示出来就够了。