获取assets目录下文件的路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/minwenping/article/details/78544586

关于这个问题网上很多回答都是转自下面的内容
这里写图片描述

第二种方法看代码就知道不靠谱,第一种方法感觉在后面就是不适用了。
下面是我自己做的路径获取代码:

File image = getFileStreamPath("image.jpg");
        File second = getFileStreamPath("second.jpg");
        Log.i(TAG, "onCreate: =path=" + image.getAbsolutePath());
        Log.i(TAG, "onCreate: =paht="+second.getAbsolutePath());
        File absoluteFile = image.getAbsoluteFile();
        if (absoluteFile.exists()) {
            Log.i(TAG, "onCreate: =文件存在=");
        } else {
            Log.i(TAG, "onCreate: =文件不存在=");
        }

运行之后效果如下:
打印出来的log:
11-15 20:09:45.770 26473-26473/? I/=minwenping=: onCreate: =path=/data/user/0/com.example.administrator.hotfixdemo/files/image.jpg
11-15 20:09:45.770 26473-26473/? I/=minwenping=: onCreate: =paht=/data/user/0/com.example.administrator.hotfixdemo/files/second.jpg
11-15 20:09:45.770 26473-26473/? I/=minwenping=: onCreate: =文件存在=

这里写图片描述


本来是系统从assetManager这个类中获取路径,结果返回的是目录下文件名,从源码注释中看出,这个方法容易鱼目混珠,只是返回文件名,路径让我们自己去拼接

   AssetManager assets = getResources().getAssets();
        try {
            String[] contents = assets.list("content");
            Log.i(TAG, "onCreate: =assets content下面文件="+contents[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }
/**
     * Return a String array of all the assets at the given path.
     * 
     * @param path A relative path within the assets, i.e., "docs/home.html".
     * 
     * @return String[] Array of strings, one for each asset.  These file
     *         names are relative to 'path'.  You can open the file by
     *         concatenating 'path' and a name in the returned string (via
     *         File) and passing that to open().
     * 
     * @see #open
     */

猜你喜欢

转载自blog.csdn.net/minwenping/article/details/78544586