How to get the android Path string to a file on Assets folder?

前端 未结 4 720
野的像风
野的像风 2020-11-27 03:29

I need to know the string path to a file on assets folder, because I\'m using a map API that needs to receive a string path, and my maps must be stored on a

4条回答
  •  星月不相逢
    2020-11-27 04:03

    You can use this method.

        public static File getRobotCacheFile(Context context) throws IOException {
            File cacheFile = new File(context.getCacheDir(), "robot.png");
            try {
                InputStream inputStream = context.getAssets().open("robot.png");
                try {
                    FileOutputStream outputStream = new FileOutputStream(cacheFile);
                    try {
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buf)) > 0) {
                            outputStream.write(buf, 0, len);
                        }
                    } finally {
                        outputStream.close();
                    }
                } finally {
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new IOException("Could not open robot png", e);
            }
            return cacheFile;
        }
    

    You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.

    In Kotlin (;D):

    @Throws(IOException::class)
    fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
        .also {
            it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
        }
    

提交回复
热议问题