Android開發(fā)實現(xiàn)文件存儲功能
本文實例為大家分享了Android開發(fā)實現(xiàn)文件存儲的具體代碼,供大家參考,具體內容如下
這個程序只有一個Activity, Activity中只有一個Edittext。實現(xiàn)的功能是在Activity銷毀之前將EditText的內容存儲到一個文件中,在Activity創(chuàng)建的時候,從該文件中讀取內容并寫道EditText中。代碼如下,在onCreate加載數(shù)據(jù),在onDestroy中保存數(shù)據(jù)。
MainActivity.kt
package com.example.filetest
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.lang.StringBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
editText.setText(loda())
}
override fun onDestroy() {
super.onDestroy()
save(editText.text.toString())
}
private fun save(inputText:String){
try {
//此函數(shù)接收兩個參數(shù),分別是文件名和打開模式
//函數(shù)的默認存儲路徑是/data/data/<package name>/file
//打開模式主要是MODE_APPEND(追加)和MODE_PRIVATE(覆蓋)
val output = openFileOutput("data", Context.MODE_PRIVATE)
val write = BufferedWriter(OutputStreamWriter(output))
write.use {
it.write(inputText)
}
}catch (e:IOException){
e.printStackTrace()
}
}
private fun loda():String{
val result = StringBuilder()
try {
val input = openFileInput("data")
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
result.append(it)
}
}
}catch (e : IOException){
e.printStackTrace()
}
return result.toString()
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="請輸入一段話"/> </LinearLayout>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android開發(fā)之日歷CalendarView用法示例
這篇文章主要介紹了Android開發(fā)之日歷CalendarView用法,簡單分析了日歷CalendarView組件的功能、屬性設置方法、界面布局、事件監(jiān)聽等相關操作技巧,需要的朋友可以參考下2019-03-03
Android使用Sqlite存儲數(shù)據(jù)用法示例
這篇文章主要介紹了Android使用Sqlite存儲數(shù)據(jù)的方法,結合實例形式分析了Android操作SQLite數(shù)據(jù)庫的相關步驟與操作技巧,需要的朋友可以參考下2016-11-11
Android調用相機并將照片存儲到sd卡上實現(xiàn)方法
Android中實現(xiàn)拍照有兩種方法,一種是調用系統(tǒng)自帶的相機,還有一種是自己用Camera類和其他相關類實現(xiàn)相機功能,這種方法定制度比較高,需要的朋友可以了解下2012-12-12

