将assets文件写入到缓存

本篇文章将介绍如何将assets 目录下的文件写入到缓存中去

前置知识

获取应用缓存目录
// /data/user/0/应用程序包名/cache/
context.getCacheDir()
如何拿到assets下的文件输入流
// InputStream open(@NonNull String fileName) 
context.getAssets().open(fileName);

核心代码

 /**
     * ,此方法的主要目的是:从assets 拷贝到 app的cache目录
     * @param context
     * @param fileName
     * @return  例如是这样:/data/user/0/com.frizzle.pluginhookandroid9/cache/plugin-debug.apk
     *
     * 不可能反正SD
     */
    public static String copyAssetToCache(Context context, String fileName) {
        //  此app的缓存目录 --> 会默认在 cache目录...,可以自己去看看哦
        File cacheDir = context.getCacheDir();
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();// TODO 如果没有缓存目录,就创建
        }
        File outPath = new File(cacheDir, fileName);// TODO 创建输出的文件位置
        if (outPath.exists()) {
            outPath.delete(); // TODO 如果该文件已经存在,就删掉
        }
        InputStream is = null; // 读取
        FileOutputStream fos = null; // 写入
        try {
            // 创建文件,如果创建成功,就返回true
            boolean res = outPath.createNewFile();
            if (res) {
                is = context.getAssets().open(fileName);// 拿到main/assets目录的输入流,用于读取字节
                fos = new FileOutputStream(outPath); // 读取出来的字节最终写到outPath
                byte[] buf = new byte[is.available()];// 缓存区
                int byteCount;

                // 开始循环读取
                while ((byteCount = is.read(buf)) != -1) {
                    fos.write(buf, 0, byteCount);
                }
                return outPath.getAbsolutePath();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // TODO  一定要记得关闭资源,为了不去性能的磨损
                fos.flush();
                is.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值