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銷毀之前將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. 不要在HTML中濫用div2. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說(shuō)明(學(xué)習(xí))3. Electron調(diào)用外接攝像頭并拍照上傳實(shí)現(xiàn)詳解4. React優(yōu)雅的封裝SvgIcon組件示例5. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)6. CSS百分比padding制作圖片自適應(yīng)布局7. TypeScript實(shí)現(xiàn)十大排序算法之歸并排序示例詳解8. vue前端RSA加密java后端解密的方法實(shí)現(xiàn)9. 深入了解React中的合成事件10. CSS清除浮動(dòng)方法匯總
