assets目录下所有文件拷贝到sd卡

来源:互联网 发布:公交查询什么软件好用 编辑:程序博客网 时间:2024/05/17 06:02
/** *  * @Description: 提供对配置文件的读写 * @author:dw * @time:2013-12-26 上午10:05:43 */public class AssetsUtil {//文件拷贝的根目录private final String BASE_PATH = Environment.getExternalStorageDirectory() + "/PadBase/assets/";/** * 将assets目录下文件拷贝到指定目录 * @param controller * */public void copyAssetsToSdCard(Context context) {AssetManager assetManager = context.getAssets();/*copy所有的文件*/getAllFiles("",assetManager);}/** * 遍历assets下全部文件 *  * @param name */private void getAllFiles(String name, AssetManager assetManager) {String[] files = null;try {files = assetManager.list(name);/* 遍历当前文件夹下所有文件及文件夹 */for (String str : files) {/* 处理是assets根目录的情况 */if (!"".equals(name)) {// 不是根目录str = name + "/" + str;} else {// 跳过assets根目录下默认的文件夹if ("images".equals(str) || "webkit".equals(str)|| "sounds".equals(str)) {continue;}}/* 文件直接复制,文件夹继续遍历 */if (str.contains(".")) { // 含有.认为是文件copyFile(str,assetManager);} else { // 文件夹getAllFiles(str,assetManager);}}} catch (IOException e) {e.printStackTrace();}}/** * 复制文件到指定目录 *  * @param fileName */private void copyFile(String fileName, AssetManager assetManager) {/*输入流*/InputStream in = null;/*输出流*/OutputStream out = null;try {/* 获得源文件的输入流 */in = assetManager.open(fileName);File outFile = new File(BASE_PATH + fileName);if (!outFile.getParentFile().exists()){ //父文件夹不存在,则新建outFile.getParentFile().mkdirs();}/*如果文件已经存在,则删除*/if (outFile.exists()) {outFile.delete();}out = new FileOutputStream(outFile);byte[] buffer = new byte[1024];int read;while ((read = in.read(buffer)) != -1) {out.write(buffer, 0, read);}out.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}}


0 0
原创粉丝点击