代码如下所示:
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= (EditText) findViewById(R.id.edit);
String input=load();
if(!TextUtils.isEmpty(input)){
editText.setText(input);
editText.setSelection(input.length());
}
}
@Override
protected void onDestroy() {
super.onDestroy();
String s=editText.getText().toString();
save(s);
}
public void save(String inputstring)
{
FileOutputStream out=null;
BufferedWriter writer=null;
try {
out=openFileOutput("shuju", Context.MODE_PRIVATE);//Context.MODE_PRIVATE是如果有同名的文件,则覆盖原文件的内容,Context.MODE_APPEND则表示如果该文件存在,就往文件里面追加内容,不存在就创建文件
writer=new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputstring);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(writer!=null)
{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String load()
{
FileInputStream in=null;
BufferedReader reader=null;
StringBuffer content=new StringBuffer();
try {
in=openFileInput("shuju");
reader=new BufferedReader(new InputStreamReader(in));
String line="";
while ((line=reader.readLine())!=null){
content.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
}