android读写assets目录资源

来源:互联网 发布:手机淘宝我的个人尺码 编辑:程序博客网 时间:2024/06/05 15:49
Android除了提供/res目录存放资源文件外,在/assets目录也会提供存放资源文件,在/assets目录下面不会在R.java里面自动生成ID,所以读取assets目录下面的资源文件需要提供路径,我们可以通过AssetManager类来访问这些文件。 
    作者需要实现从 A.apk( 资源apk ,把所有的资源如:so、apk、可执行文件等放到assets目录下面,apk没有实现逻辑代码)拷贝资源到指定目录下,所以作者创建了一个实现资源拷贝逻辑的 B.apk( 一个Service,也可用Activity实现),由于拷贝路径一般情况下是不可访问或者创建的(每个apk安装之后只能访问/data/data/自己包名/下面的私有空间),作者需要这个apk能够获取系统权限(System权限),则必须在AndroidManifest.xml声明shareduserid,具体如何操作下一节进行记录。 


一、AssetManager读取文件常用的几个API

    1.文件读取方式
    AssetManager.open(String filename),返回的是一个InputSteam类型的字节流,这里的filename必须是文件,而不能是文件夹,AssetManager打开资源文件的open方法是一个重载方法,可以添加一个打开方式的int参数,根据参数不同可做相应操作。具体请看官方文档http://web.mit.edu/clio/MacData/afs/sipb/project/android/docs/reference/android/content/res/AssetManager.html
    2.资源文件是可以存在文件夹以及子目录
    public final String[]list(String path),返回当前目录下面的所有文件以及子目录的名称。可以通过递归遍历整个文件目录,实现所有资源文件的访问。String[] Array of strings, one for each asset. These file names are relative to 'path'. You can open the file by concatenating 'path' and a name in the returned string (via File) and passing that to open().

二、相关实现代码
资源APK(A.apk)


具体实现代码片段,由于使用系统权限,生成的路径可以自己改一下B.apk

public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);try {ctxDealFile = this.createPackageContext("com.zlc.ipanel",Context.CONTEXT_IGNORE_SECURITY);} catch (NameNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}btn3.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubtry {String uiFileName = "ipanelJoin";deepFile(ctxDealFile, uiFileName);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();textView.setText("file is wrong");}}});//}public void deepFile(Context ctxDealFile, String path) {try {String str[] = ctxDealFile.getAssets().list(path);if (str.length > 0) {//如果是目录File file = new File("/data/" + path);file.mkdirs();for (String string : str) {path = path + "/" + string;System.out.println("zhoulc:\t" + path);// textView.setText(textView.getText()+"\t"+path+"\t");deepFile(ctxDealFile, path);path = path.substring(0, path.lastIndexOf('/'));}} else {//如果是文件InputStream is = ctxDealFile.getAssets().open(path);FileOutputStream fos = new FileOutputStream(new File("/data/"+ path));byte[] buffer = new byte[1024];int count = 0;while (true) {count++;int len = is.read(buffer);if (len == -1) {break;}fos.write(buffer, 0, len);}is.close();fos.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}