Android 获取assets文件夹下面的文件路径

用加载本地web资源文件暴力获取的方式:

 String path = "file:///android_asset/平舆.tile";

结果在这里不可行,在网上查询了很多资料,思路大致就是先把文件复制到缓存中,然后再获取文件的路径。代码如下所示:"平舆.tile"是assets文件夹下面的文件,我这里的文件路径是:我这里直接是一级目录,如果目录是多个层级,也只要用最终层级就可以了,比如我这里就是平舆.tile

String path=copyAssetGetFilePath("平舆.tile");

获取路径代码

private String copyAssetGetFilePath(String fileName) {
    try {
        File cacheDir = getContext().getCacheDir();
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
        File outFile = new File(cacheDir, fileName);
        if (!outFile.exists()) {
            boolean res = outFile.createNewFile();
            if (!res) {
                return null;
            }
        } else {
            if (outFile.length() > 10) {//表示已经写入一次
                return outFile.getPath();
            }
        }
        InputStream is = getContext().getAssets().open(fileName);
        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;
}

 

最终可以把path处理成File;

File file = new File(path);

问题总算是解决了。

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值