下面这个类,主要功能是通过递归方式,实现对assets下的某个子目录文件读取操作,并复制到指定路径。
-
package com.study.asset;
-
-
import java.io.File;
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
import java.io.InputStream;
-
-
import com.study.mylog.MyLog;
-
-
import android.content.Context;
-
import android.content.res.AssetManager;
-
-
public
class AssetsCopy {
-
-
private Context mContext;
-
public AssetsCopy(Context context) {
-
mContext = context;
-
}
-
-
public boolean CopyFiles(String oldPath, String newPath) throws IOException {
-
boolean isCopy =
true;
-
AssetManager mAssetManger = mContext.getAssets();
-
String[] fileNames=mAssetManger.list(oldPath);
// 获取assets目录下的所有文件及有文件的目录名
-
-
if (fileNames.length >
0) {
//如果是目录,如果是具体文件则长度为0
-
File file =
new File(newPath);
-
file.mkdirs();
//如果文件夹不存在,则递归
-
for (String fileName : fileNames) {
-
if(oldPath==
"")
//assets中的oldPath是相对路径,不能够以“/”开头
-
CopyFiles(fileName,newPath+
"/"+fileName);
-
else
-
CopyFiles(oldPath+
"/"+fileName,newPath+
"/"+fileName);
-
}
-
}
else {
//如果是文件
-
InputStream is = mAssetManger.open(oldPath);
-
FileOutputStream fos =
new FileOutputStream(
new File(newPath));
-
byte[] buffer =
new
byte[
1024];
-
int byteCount=
0;
-
while((byteCount=is.read(buffer))!=-
1) {
//循环从输入流读取 buffer字节
-
fos.write(buffer,
0, byteCount);
//将读取的输入流写入到输出流
-
}
-
fos.flush();
//刷新缓冲区
-
is.close();
-
fos.close();
-
}
-
return isCopy;
-
}
-
-
}