Android開(kāi)發(fā)實(shí)現(xiàn)文件存儲(chǔ)功能
本文實(shí)例為大家分享了Android開(kāi)發(fā)實(shí)現(xiàn)文件存儲(chǔ)的具體代碼,供大家參考,具體內(nèi)容如下
這個(gè)程序只有一個(gè)Activity, Activity中只有一個(gè)Edittext。實(shí)現(xiàn)的功能是在Activity銷(xiāo)毀之前將EditText的內(nèi)容存儲(chǔ)到一個(gè)文件中,在Activity創(chuàng)建的時(shí)候,從該文件中讀取內(nèi)容并寫(xiě)道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ù),分別是文件名和打開(kāi)模式 //函數(shù)的默認(rèn)存儲(chǔ)路徑是/data/data/<package name>/file //打開(kāi)模式主要是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. 推薦一個(gè)好看Table表格的css樣式代碼詳解2. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介3. asp批量添加修改刪除操作示例代碼4. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法5. 刪除docker里建立容器的操作方法6. asp在iis7報(bào)錯(cuò)行號(hào)不準(zhǔn)問(wèn)題的解決方法7. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效8. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作?!钡脑幃悊?wèn)題……9. asp讀取xml文件和記數(shù)10. 概述IE和SQL2k開(kāi)發(fā)一個(gè)XML聊天程序
