網(wǎng)站首頁 編程語言 正文
本地存儲(chǔ)案例
該方法僅適用于保存一些比較簡單的,運(yùn)行時(shí)并不占用過多內(nèi)存的小字段
原理介紹
我們需要完成這么一個(gè) app:
- 在文本框輸入文字后退出 app 會(huì)自動(dòng)存儲(chǔ)
- 下次打開后,檢測到存儲(chǔ)的文本文件,自動(dòng)獲取他并輸出到文本框里
首先需要清楚:
本案例文件存儲(chǔ)的位置是:data/data/你的工程包名/files/xxx
當(dāng)手機(jī)內(nèi)存不夠時(shí),data/data
目錄下的文件會(huì)被自動(dòng)清理以騰出空間,所以本方法不具有持久化存儲(chǔ)的功效!
下面介紹幾個(gè)獲取不同存儲(chǔ)路徑的方法:
- 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/
一般的,由于目前手機(jī)都是一體機(jī)且無法再擴(kuò)展外存,所以存儲(chǔ)到 SD 卡的解決方式可行性較高!
設(shè)置文本輸入框
在 mainactivity 的布局文件隨意添加一個(gè)文本輸入框
<?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>
存儲(chǔ)讀取數(shù)據(jù)
首先我們需要定義一個(gè)存儲(chǔ)文件的方法
private fun save(inputText: String) { try { // 打開輸出文件,如果不存在就新建一個(gè) val output = openFileOutput("data", Context.MODE_PRIVATE) // 設(shè)置輸出流 val writer = BufferedWriter(OutputStreamWriter(output)) // 使用use語法,在輸出所有內(nèi)容完畢后就會(huì)自動(dòng)關(guān)閉流,不需要手動(dòng)關(guān)閉了! writer.use { it.write(inputText) } } catch (e: IOException) { e.printStackTrace() } }
既然有了存儲(chǔ),那必須還有一個(gè)讀取,依葫蘆畫瓢即可
private fun load(): String { // 存儲(chǔ)獲取到的文本 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() }
理解完以上兩個(gè)主要代碼后,我們組合到 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打開前讀取存儲(chǔ)的文件,拿出內(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í)行存儲(chǔ)方法 override fun onDestroy() { super.onDestroy() val inputText = editText.text.toString() save(inputText) } // 存儲(chǔ) 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,直接點(diǎn)擊測試就可以看到結(jié)果了!
原文鏈接:https://blog.csdn.net/delete_you/article/details/127186803
相關(guān)推薦
- 2022-02-19 DevTools 無法加載 SourceMap 錯(cuò)誤:狀態(tài)代碼 404,netERR_HTTP_RE
- 2022-06-07 如何在Python中妥善使用進(jìn)度條詳解_python
- 2024-03-25 Intellij IDEA 啟動(dòng)tomcat報(bào)錯(cuò)
- 2023-02-04 python中各種路徑設(shè)置的方法詳解_python
- 2022-04-12 python入門之scrapy框架中Request對象和Response對象的介紹_python
- 2022-07-20 nginx?添加http_stub_status_module模塊_nginx
- 2022-04-12 iOS?block的值捕獲與指針捕獲詳解_IOS
- 2022-05-31 在.NET?MAUI應(yīng)用中配置應(yīng)用生命周期事件_實(shí)用技巧
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支