Android開發(fā)實(shí)現(xiàn)文件存儲功能
本文實(shí)例為大家分享了Android開發(fā)實(shí)現(xiàn)文件存儲的具體代碼,供大家參考,具體內(nèi)容如下
這個程序只有一個Activity, Activity中只有一個Edittext。實(shí)現(xiàn)的功能是在Activity銷毀之前將EditText的內(nèi)容存儲到一個文件中,在Activity創(chuàng)建的時候,從該文件中讀取內(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ù)接收兩個參數(shù),分別是文件名和打開模式 //函數(shù)的默認(rèn)存儲路徑是/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='請輸入一段話'/></LinearLayout>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera2. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……3. xml中的空格之完全解說4. asp讀取xml文件和記數(shù)5. 告別AJAX實(shí)現(xiàn)無刷新提交表單6. asp批量添加修改刪除操作示例代碼7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法9. asp中response.write("中文")或者js中文亂碼問題10. CSS3中Transition屬性詳解以及示例分享
