Android開發(fā)實(shí)現(xiàn)文件存儲(chǔ)功能
本文實(shí)例為大家分享了Android開發(fā)實(shí)現(xiàn)文件存儲(chǔ)的具體代碼,供大家參考,具體內(nèi)容如下
這個(gè)程序只有一個(gè)Activity, Activity中只有一個(gè)Edittext。實(shí)現(xiàn)的功能是在Activity銷毀之前將EditText的內(nèi)容存儲(chǔ)到一個(gè)文件中,在Activity創(chuàng)建的時(shí)候,從該文件中讀取內(nèi)容并寫道EditText中。代碼如下,在onCreate加載數(shù)據(jù),在onDestroy中保存數(shù)據(jù)。
MainActivity.kt
package com.example.filetestimport android.content.Contextimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport kotlinx.android.synthetic.main.activity_main.*import java.io.*import java.lang.StringBuilderclass 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ù)接收兩個(gè)參數(shù),分別是文件名和打開模式 //函數(shù)的默認(rèn)存儲(chǔ)路徑是/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: android:layout_width='wrap_content' android:layout_height='wrap_content' android:hint='請(qǐng)輸入一段話'/></LinearLayout>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題4. 圖文詳解vue中proto文件的函數(shù)調(diào)用5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. 什么是python的自省7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備