You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何保存Uri类型路径至平面文件并恢复后赋值给ImageView

保存Uri路径到平面文件并恢复用于ImageView显示

已实现的保存逻辑

将输入字符串与Uri转为字符串后用#分隔,写入MisComidas.txt文件,代码如下:

private fun saveToFile(){
   try {
            val archivo = OutputStreamWriter(openFileOutput("MisComidas.txt", MODE_APPEND))
            val text= binding.etComida.text.toString()+"#"+imgUri.toString()+"\n"

            archivo.write(text)
            archivo.flush()
            archivo.close()
    } catch (_: IOException) {
    }
    Toast.makeText(this, "Comida-->${dataSet.size} Guardada Correctamente" ,Toast.LENGTH_SHORT).show()
}

读取并恢复Uri的实现

读取文件时将分割后的字符串转回Uri类型,添加到数据集供RecyclerView加载显示图片,读取方法代码如下:

private fun readFile(){
    if (fileList().contains("MisComidas.txt")) {
        try {
            var texto = ""
            val archivo = InputStreamReader(openFileInput("MisComidas.txt"))
            val br = BufferedReader(archivo)
            var linea = br.readLine()
            while (linea != null) {

                val pos1 = linea.indexOf("#")
                val str = linea.substring(0, pos1)
                val str1 = (linea.substring(pos1+1)).toUri()

                dataSet.add(ComidaData(str,str1))
                texto = texto + linea + "\n"
                linea = br.readLine()
            }
            br.close()
            archivo.close()
        } catch (_: IOException) {
        }
    }
}

内容的提问来源于stack exchange,提问作者CVtec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:16:25