当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发实现文件存储功能

Android开发实现文件存储功能

2020年07月28日  | 移动技术网移动技术  | 我要评论

本文实例为大家分享了android开发实现文件存储的具体代码,供大家参考,具体内容如下

这个程序只有一个activity, activity中只有一个edittext。实现的功能是在activity销毁之前将edittext的内容存储到一个文件中,在activity创建的时候,从该文件中读取内容并写道edittext中。代码如下,在oncreate加载数据,在ondestroy中保存数据。

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 {
   //此函数接收两个参数,分别是文件名和打开模式
   //函数的默认存储路径是/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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网