栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将目录从资产复制到数据文件夹

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将目录从资产复制到数据文件夹

尝试使用您的Application实例的以下代码(您应该在清单中编写该类):该代码将资产/文件文件夹的内容复制到应用程序的缓存文件夹中(您可以将其他路径放在copyAssetFolder()函数中)。仅在首次启动应用程序时

import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.app.Application;import android.content.Context;import android.content.res.AssetManager;import android.preference.PreferenceManager;public class MyApplication extends Application {    private static Context  s_sharedContext;    @Override    public void onCreate () {        super.onCreate();if (!PreferenceManager.getDefaultSharedPreferences(     getApplicationContext()) .getBoolean("installed", false)) { PreferenceManager.getDefaultSharedPreferences(         getApplicationContext())     .edit().putBoolean("installed", true).commit(); copyAssetFolder(getAssets(), "files",          "/data/data/com.example.appname/files");        }    }    private static boolean copyAssetFolder(AssetManager assetManager, String fromAssetPath, String toPath) {        try { String[] files = assetManager.list(fromAssetPath); new File(toPath).mkdirs(); boolean res = true; for (String file : files)     if (file.contains("."))         res &= copyAsset(assetManager,       fromAssetPath + "/" + file,      toPath + "/" + file);     else          res &= copyAssetFolder(assetManager,       fromAssetPath + "/" + file,      toPath + "/" + file); return res;        } catch (Exception e) { e.printStackTrace(); return false;        }    }    private static boolean copyAsset(AssetManager assetManager, String fromAssetPath, String toPath) {        InputStream in = null;        OutputStream out = null;        try {          in = assetManager.open(fromAssetPath);          new File(toPath).createNewFile();          out = new FileOutputStream(toPath);          copyFile(in, out);          in.close();          in = null;          out.flush();          out.close();          out = null;          return true;        } catch(Exception e) { e.printStackTrace(); return false;        }    }    private static void copyFile(InputStream in, OutputStream out) throws IOException {        byte[] buffer = new byte[1024];        int read;        while((read = in.read(buffer)) != -1){          out.write(buffer, 0, read);        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469967.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号