Android实现文件保存数据,读取数据
首先在布局文件里面创建一个EditText id为edit
然后开始写java文件
package com.yan.filesave; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; /** * 存储瞬时数据到文件里面,退出程序后 * 当你打开程序的时候,自动取出文件里面数据,并且填充到对应的视图里面 */ public class MainActivity extends AppCompatActivity { private EditText edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit=(EditText)findViewById(R.id.edit); //读取文件 load()为读取文件的方法 String inputText=load(); //读取文件后设置edittext的值 //判断是否为null或者空 if(!TextUtils.isEmpty(inputText)){ edit.setText(inputText); edit.setSelection(inputText.length());//移动光标到末尾以便继续输入 Toast.makeText(this, "Restoring succeded", Toast.LENGTH_SHORT).show(); } } private String load() { FileInputStream in=null; BufferedReader reader=null; StringBuilder content=new StringBuilder(); try { in=openFileInput("data"); reader=new BufferedReader(new InputStreamReader(in)); String line=""; //一行一行读取 while((line=reader.readLine())!=null){ content.append(line); } } catch (IOException e) { e.printStackTrace(); }finally { if(reader!=null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return content.toString(); } @Override protected void onDestroy() { super.onDestroy(); //在回收的时候先存储数据到文件 String inputText=edit.getText().toString(); save(inputText); } /** * 存储文件的方法 * @param inputText */ private void save(String inputText) { FileOutputStream out=null; BufferedWriter writer=null; try { out=openFileOutput("data", Context.MODE_PRIVATE); writer=new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(writer!=null){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30