美文网首页
Android开发数据存储之持久化技术(1)文件存储

Android开发数据存储之持久化技术(1)文件存储

作者: 别看后面有人 | 来源:发表于2021-07-02 17:54 被阅读0次

文件存储是Android中最基本的存储方式,它不对存储的内容进行格式化处理,所有的数据都原封不动的保存到文件中,因而它适合存储一些简单的文本或者二进制数据。
一、将文件存储到文件中
文件存储默认的路径:/data/data/<package name> file目录下

 fun sava(inputText:String){
        val output=openFileOutput("data",Context.MODE_PRIVATE)
        val write=BufferedWriter(OutputStreamWriter(output))
        write.use {
            it.write(inputText)
        }
    }

代码中openFileOutput方法,可以用于将数据存储到指定的文件中,这个方法接收两个参数,第一个参数是文件名,在文件创建的时候使用,第二个参数是文件的操作模式,主要有MODE_PRIVATE和MODE_APPEND,MODE_PRIVATE表示当指定相同文件名的时候,所写入的内容会覆盖原文件的内容,而MODE_APPEND表示如果该文件已经存在,就往文件里面追加内容,不存在创建新文件。openFileOutput返回的是一个FileOutputStream对象,得到这个对象之后就使用java流的方式写入文件,然后构建出一个OutputStreamWriter对象,接着构建一个BufferedWriter对象,这样就可以通过BufferedWriter将文本写入文件中。write使用了一个use函数。
调用:
xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入文字" />
</LinearLayout>
class FileActivity:ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_file)
    }

    override fun onDestroy() {
        super.onDestroy()
        val inputtext=edText.text.toString()
        sava(inputtext)
    }
    fun sava(inputText:String){
        val output=openFileOutput("data",Context.MODE_PRIVATE)
        val write=BufferedWriter(OutputStreamWriter(output))
        write.use {
            it.write(inputText)
        }
    }
}

在activity销毁之前一定要调用这个方法,在onDestroy()方法中,获取EditText中输入内容,并调用sava方法。
调试的时候按返回键退出程序,然后ctrl+shift+A搜索“Device File Explore,然后在data/data/com.app.activitytest/file,如下图:


image.png

相关文章

网友评论

      本文标题:Android开发数据存储之持久化技术(1)文件存储

      本文链接:https://www.haomeiwen.com/subject/mlzjultx.html