[转载]
apk安装以后放在/data/app/**.apk,以apk形式存在,asset/res和apk在一起,并不会解压到/data/data/XXX 目录下去,所以是无法直接获取到assets的绝对路径,因为它根本没有我们想要的绝对路径;
因此我们只能通过文件读写的方式,写到缓存文件里面去,通过获取缓存文件路径 来读取,见如下代码 ,byte的size根据自己文件大小来确认,可自己调整。

public String copyAssetGetFilePath(String assetsFilename) {

        try {
            File filesDir = mContext.getFilesDir();
            if (!filesDir.exists()) {
                filesDir.mkdirs();
            }
            File outFile = new File(filesDir, assetsFilename);
            String outFilename = outFile.getAbsolutePath();
            Log.i(TAG, "outFile is " + outFilename);
            if (!outFile.exists()) {
                boolean res = outFile.createNewFile();
                if (!res) {
                    Log.e(TAG, "outFile not exist!(" + outFilename + ")");
                    return null;
                }
            }
            InputStream is = mContext.getAssets().open(assetsFilename);

            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return outFile.getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐