網(wǎng)站首頁 編程語言 正文
本地存儲案例
該方法僅適用于保存一些比較簡單的,運行時并不占用過多內(nèi)存的小字段
原理介紹
我們需要完成這么一個 app:
- 在文本框輸入文字后退出 app 會自動存儲
- 下次打開后,檢測到存儲的文本文件,自動獲取他并輸出到文本框里
首先需要清楚:
本案例文件存儲的位置是:data/data/你的工程包名/files/xxx
當手機內(nèi)存不夠時,data/data
目錄下的文件會被自動清理以騰出空間,所以本方法不具有持久化存儲的功效!
下面介紹幾個獲取不同存儲路徑的方法:
- getCacheDir():/data/data/你的應(yīng)用的包名/cache
- getFilesDir():/data/data/你的應(yīng)用的包名/files
- getExternalFilesDir():SDCard/Android/data/你的應(yīng)用的包名/files/
- getExternalCacheDir():SDCard/Android/data/你的應(yīng)用包名/cache/
一般的,由于目前手機都是一體機且無法再擴展外存,所以存儲到 SD 卡的解決方式可行性較高!
設(shè)置文本輸入框
在 mainactivity 的布局文件隨意添加一個文本輸入框
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:hint="請輸入內(nèi)容"/> </LinearLayout>
存儲讀取數(shù)據(jù)
首先我們需要定義一個存儲文件的方法
private fun save(inputText: String) { try { // 打開輸出文件,如果不存在就新建一個 val output = openFileOutput("data", Context.MODE_PRIVATE) // 設(shè)置輸出流 val writer = BufferedWriter(OutputStreamWriter(output)) // 使用use語法,在輸出所有內(nèi)容完畢后就會自動關(guān)閉流,不需要手動關(guān)閉了! writer.use { it.write(inputText) } } catch (e: IOException) { e.printStackTrace() } }
既然有了存儲,那必須還有一個讀取,依葫蘆畫瓢即可
private fun load(): String { // 存儲獲取到的文本 val content = StringBuilder() try { // 打開文件 val input = openFileInput("data") // 設(shè)置輸入流 val reader = BufferedReader(InputStreamReader(input)) reader.use { // 逐行輸入到content變量 reader.forEachLine { content.append(it) } } } catch (e: IOException) { e.printStackTrace() } // 返回得到的文字文本數(shù)據(jù) return content.toString() }
理解完以上兩個主要代碼后,我們組合到 MainActivity.kt
文件內(nèi),最終得到的代碼如下:
package com.zhiyiyi.listviewdemo import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* import java.io.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // activity打開前讀取存儲的文件,拿出內(nèi)容 val inputText = load() if (inputText.isNotEmpty()) { editText.setText(inputText) editText.setSelection(inputText.length) Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show() } } // activity銷毀前執(zhí)行存儲方法 override fun onDestroy() { super.onDestroy() val inputText = editText.text.toString() save(inputText) } // 存儲 private fun save(inputText: String) { try { val output = openFileOutput("data", Context.MODE_PRIVATE) val writer = BufferedWriter(OutputStreamWriter(output)) writer.use { it.write(inputText) } } catch (e: IOException) { e.printStackTrace() } } // 讀取 private fun load(): String { val content = StringBuilder() try { val input = openFileInput("data") val reader = BufferedReader(InputStreamReader(input)) reader.use { reader.forEachLine { content.append(it) } } } catch (e: IOException) { e.printStackTrace() } return content.toString() } }
END,直接點擊測試就可以看到結(jié)果了!
原文鏈接:https://blog.csdn.net/delete_you/article/details/127186803
相關(guān)推薦
- 2022-09-15 Go語言操作redis數(shù)據(jù)庫的方法_Golang
- 2022-09-18 GO語言原生實現(xiàn)文件上傳功能_Golang
- 2022-10-07 Android?drawFunctor?原理及應(yīng)用詳情_Android
- 2022-01-11 Cookie、sessionStorage和localStorage的區(qū)別
- 2022-10-05 使用python?matplotlib?contour畫等高線圖的詳細過程講解_python
- 2023-03-16 Android藍牙服務(wù)啟動流程分析探索_Android
- 2022-11-18 Python實現(xiàn)常見數(shù)據(jù)格式轉(zhuǎn)換的方法詳解_python
- 2023-01-09 基于Go語言實現(xiàn)插入排序算法及優(yōu)化_Golang
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支