android读写assets目录下面的资源文件(文件夹)
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,具体如何操做下一节进行记录。
1、AssetManager读取文件经常使用的几个API html
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(). java
2、相关实现代码
资源APK(A.apk)

具体实现代码片断,因为使用系统权限,生成的路径能够本身改一下B.apk android
01 |
public void onCreate(Bundle savedInstanceState) { |
02 |
super.onCreate(savedInstanceState); |
03 |
setContentView(R.layout.main); |
05 |
ctxDealFile = this.createPackageContext("com.zlc.ipanel", |
06 |
Context.CONTEXT_IGNORE_SECURITY); |
07 |
} catch (NameNotFoundException e1) { |
08 |
// TODO Auto-generated catch block |
12 |
btn3.setOnClickListener(new OnClickListener() { |
14 |
public void onClick(View v) { |
15 |
// TODO Auto-generated method stub |
17 |
String uiFileName = "ipanelJoin"; |
18 |
deepFile(ctxDealFile, uiFileName); |
19 |
} catch (Exception e) { |
20 |
// TODO Auto-generated catch block |
22 |
textView.setText("file is wrong"); |
28 |
public void deepFile(Context ctxDealFile, String path) { |
30 |
String str[] = ctxDealFile.getAssets().list(path); |
31 |
if (str.length > 0) {//若是是目录 |
32 |
File file = new File("/data/" + path); |
34 |
for (String string : str) { |
35 |
path = path + "/" + string; |
36 |
System.out.println("zhoulc:\t" + path); |
37 |
// textView.setText(textView.getText()+"\t"+path+"\t"); |
38 |
deepFile(ctxDealFile, path); |
39 |
path = path.substring(0, path.lastIndexOf('/')); |
42 |
InputStream is = ctxDealFile.getAssets().open(path); |
43 |
FileOutputStream fos = new FileOutputStream(new File("/data/" |
45 |
byte[] buffer = new byte[1024]; |
49 |
int len = is.read(buffer); |
53 |
fos.write(buffer, 0, len); |
58 |
} catch (IOException e) { |
59 |
// TODO Auto-generated catch block |