参考链接:
http://blog.youkuaiyun.com/qq_17326933/article/details/48450487
注意点:
1、比如文件 text.txt 不应直接放在 assets 下,至少有个路劲:比如 assets/copyfile/text.txt。尝试没有添加路劲,使用下面的帮助类会失败
2、楼主感觉很久也没跟新了,秒速得有些东西也是有问题的。我帮楼主继续下去吧。
工具类代码:
/**
* @author admin
* 复制assets下面的protectedfile下面的 issmvw.cfg 文件到 sdcardPath 中
*/
public class AssetsCopyToSDcard {
Context context;
public AssetsCopyToSDcard(Context context) {
super();
this.context = context;
}
/**
* @param context
* @param assetpath asset下的路径
* @param SDpath SDpath下保存路径
*/
public void AssetToSD(String assetpath, String SDpath) {
AssetManager asset = context.getAssets();
// 循环的读取asset下的文件,并且写入到SD卡
String[] filenames = null;
FileOutputStream out = null;
InputStream in = null;
try {
filenames = asset.list(assetpath);
if (filenames.length > 0) {// 说明是目录
// 创建目录
getDirectory(assetpath);
for (String fileName : filenames) {
AssetToSD(assetpath + "/" + fileName, SDpath + "/" + fileName);
}
} else {
// 说明是文件,直接复制到SD卡
File SDFlie = new File(SDpath);
String path = assetpath.substring(0, assetpath.lastIndexOf("/"));
getDirectory(path);
if (!SDFlie.exists()) {
SDFlie.createNewFile();
}
// 将内容写入到文件中
in = asset.open(assetpath);
out = new FileOutputStream(SDFlie);
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = in.read(buffer)) != -1) {
out.write(buffer, 0, byteCount);
}
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
/**
* 关闭报错,java.lang.RuntimeException: Unable to start activity
* ComponentInfo
* {com.example.wealth/com.example.wealth.UI.main}:
* java.lang.RuntimeException: Assetmanager has been closed
*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 分级建立文件夹
public void getDirectory(String path) {
// 对SDpath进行处理,分层级建立文件夹
String[] s = path.split("/");
String str = Environment.getExternalStorageDirectory().toString();
for (int i = 0; i < s.length; i++) {
str = str + "/" + s[i];
File file = new File(str);
if (!file.exists()) {
file.mkdir();
}
}
}
}
使用方法
String assetFilePath = "protectedfile/test.txt";
String sdcardFileResPath = Environment.getExternalStorageDirectory().toString()
+ "/test/test.txt";
AssetsCopyToSDcard assetsCopyTOSDcard = new AssetsCopyToSDcard(Context);
assetsCopyTOSDcard.AssetToSD(assetFilePath, sdcardFileResPath);
注:其中 Context 传当前类的上下文,不懂上下文的请百度查阅。
总结
好东西,真的有必要分享出来给大家工程师程序猿,但是尽量应该验证好。节省大家的时间,同时考虑初学者,有些不太明白的,应该说明。让初学者更加容易明白,上手使用这些。