日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Android本地存儲(chǔ)方法淺析介紹_Android

作者:知奕奕 ? 更新時(shí)間: 2022-11-22 編程語言

本地存儲(chǔ)案例

該方法僅適用于保存一些比較簡單的,運(yùn)行時(shí)并不占用過多內(nèi)存的小字段

原理介紹

我們需要完成這么一個(gè) app:

  1. 在文本框輸入文字后退出 app 會(huì)自動(dòng)存儲(chǔ)
  2. 下次打開后,檢測到存儲(chǔ)的文本文件,自動(dòng)獲取他并輸出到文本框里

首先需要清楚:

本案例文件存儲(chǔ)的位置是:data/data/你的工程包名/files/xxx

當(dāng)手機(jī)內(nèi)存不夠時(shí),data/data 目錄下的文件會(huì)被自動(dòng)清理以騰出空間,所以本方法不具有持久化存儲(chǔ)的功效!

下面介紹幾個(gè)獲取不同存儲(chǔ)路徑的方法:

  1. getCacheDir():/data/data/你的應(yīng)用的包名/cache
  2. getFilesDir():/data/data/你的應(yīng)用的包名/files
  3. getExternalFilesDir():SDCard/Android/data/你的應(yīng)用的包名/files/
  4. 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

欄目分類
最近更新