Android数据存储方式之文件存储

2021-09-10 11:33:13 浏览数 (1)

文件存储是Android中数据存储的基本方式之一,Android提供了openFileOutputopenFileInput两个方法来提供FileOutStreamFileInputStream,文件将会存储在APP的数据目录中(一般是/data/data/APP包名)。

下面是一个简单的示例

FileStorageActivity的布局文件如下:

代码语言:html复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp"
    tools:context=".FileStorageActivity">
    <EditText
        android:id="@ id/fileEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp" />
    <Button
        android:id="@ id/fileWriteButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="写入数据" />
    <Button
        android:id="@ id/fileReadButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读取数据" />
</LinearLayout>

FileStorageActivity

代码语言:java复制
package cn.titan6.data.storage.demo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import java.io.*
class FileStorageActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_storage)
        val editText: EditText = findViewById(R.id.fileEditText)
        val writeButton: Button = findViewById(R.id.fileWriteButton)
        val readButton: Button = findViewById(R.id.fileReadButton)
        writeButton.setOnClickListener {
            saveFileData(editText.text.toString())
            Log.i("FileStorageActivity", "Save data finished")
            editText.setText("")
        }
        readButton.setOnClickListener {
            val str = readFileData()
            Log.i("FileStorageActivity", "Read data finished")
            editText.setText(str)
        }
    }
    private fun saveFileData(str: String) {
        val openFileOutput = openFileOutput("data", MODE_PRIVATE)
        val writer = BufferedWriter(OutputStreamWriter(openFileOutput))
        writer.use {
            it.write(str)
        }
    }
    private fun readFileData(): String {
        val content = StringBuilder()
        val input = openFileInput("data")
        val reader = BufferedReader(InputStreamReader(input))
        reader.use {
            reader.forEachLine {
                content.append(it)
            }
        }
        return content.toString()
    }
}

本文为本人原创文章,同步发布于Titan笔记

https://www.titan6.cn/archives/343.html

0 人点赞