56. (android Development) file read / write operations OpenFileOutput and OpenFileInput

Keywords: Android xml encoding

In addition to saving key value data, content can also be saved directly in the form of files in android. Data format can be at will, are in the form of strings in the file. Take the longest txt text file you can see as an example.
To read and write files, you need to open them. There are two methods: OpenFileOutput and OpenFileInput
The storage location of these two methods in android is / data / data / < package name > / files
Write an interface code first

<?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="Save data" />

    <Button
        android:id="@+id/btnLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Read data" />
</LinearLayout>

Initial interface

Then write the kotlin code.
Add two button click actions to onCreate

        // Write data to data.txt
        btnSave.setOnClickListener {
            try {
                val fileOutput = openFileOutput("data.txt", Activity.MODE_PRIVATE)
                val str = "The heart of a child, the rhinoceros looking at the moon, is always a warrior. Patience, carefulness, confidence and perseverance."
                fileOutput.write(str.toByteArray(Charsets.UTF_8))
                fileOutput.close()
                Toast.makeText(this, "Data saved successfully!", Toast.LENGTH_LONG).show()
            } catch (e: Exception) {
            }
        }
        // Read data in data.txt
        btnLoad.setOnClickListener {
            try {
                val fileInput = openFileInput("data.txt")
                fileInput.reader().forEachLine { ttvwData.setText(it) }
                fileInput.close()
            } catch (e: Exception) {
            }
        }
Show results

Posted by apenster on Sat, 02 May 2020 19:08:17 -0700