<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edittext"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=findViewById(R.id.edittext);
String inputText=load();
if (!TextUtils.isEmpty(inputText)){
editText.setText(inputText);
editText.setSelection(inputText.length());
Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
String inputText=editText.getText().toString();
save(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 (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;
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 (Exception e) {
e.printStackTrace();
} finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
}