56. (android开发)文件读写操作OpenFileOutput和OpenFileInput

除了保存key-value数据,在android中也可以直接以文件的形式保存内容。数据格式就可以随意了,都是按照字符串的形式存在文件里的。就以最长见到的 txt 文本文件为例子吧。
读写文件都需要打开文件,离不开两个方法:OpenFileOutput 和 OpenFileInput
这两个方法针对的文件,在 android 中的存储位置是 /data/data/<package name>/files
先写一个界面代码

<?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"
    tools:context="com.cofox.functions.OpenFileOutuutAndOpenFileInput.OpenFileOutputActivity">

    <TextView
        android:id="@+id/ttvwData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存数据" />

    <Button
        android:id="@+id/btnLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读取数据" />
</LinearLayout>

初始界面

然后写 kotlin 代码。
在 onCreate 中增加两个按钮的点击动作

        // 向 data.txt 写入数据
        btnSave.setOnClickListener {
            try {
                val fileOutput = openFileOutput("data.txt", Activity.MODE_PRIVATE)
                val str = "赤子之心,犀牛望月,永是勇士。耐心、细心、信心、恒心。"
                fileOutput.write(str.toByteArray(Charsets.UTF_8))
                fileOutput.close()
                Toast.makeText(this, "数据保存成功!", Toast.LENGTH_LONG).show()
            } catch (e: Exception) {
            }
        }
        // 读取 data.txt 中的数据
        btnLoad.setOnClickListener {
            try {
                val fileInput = openFileInput("data.txt")
                fileInput.reader().forEachLine { ttvwData.setText(it) }
                fileInput.close()
            } catch (e: Exception) {
            }
        }
显示结果
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android开发中,离不开对文件的操作。本文首先介绍了使用java对文件进行基本的读写操作,而后介绍了A...
    baolvlv阅读 12,094评论 0 5
  • 1.引言   一般在做一些面试题的时候,Android有几种数据存储方案这个问题是经常碰到的。在我们实际应用中,任...
    忆念成风阅读 2,176评论 0 10
  • 一、Android缓存机制 Android缓存分为内存缓存和文件缓存(磁盘缓存)。在早期,各大图片缓存框架流行之前...
    流水潺湲阅读 38,252评论 3 33
  • 面试题总结 通用 安卓学习途径, 寻找资料学习的博客网站 AndroidStudio使用, 插件使用 安卓和苹果的...
    JingBeibei阅读 1,724评论 2 21
  • 昨晚做了个梦,今晚寻思着要不要继续做下去呢? 梦中的我特别兴奋地跑到大润发买了一个超大超大,大到可以把我的头塞进去...
    作家梁晶晶阅读 334评论 0 6