//布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<EditText android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:hint="Type something here"/>
</LinearLayout>
//例子
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText)findViewById(R.id.edit);
String inputText = load();
if (!TextUtils.isEmpty(inputText)){
edit.setText(inputText);
edit.setSelection(inputText.length());
Toast.makeText(this,"Restoring succeede",Toast.LENGTH_SHORT).show();
}else{
Log.d("123","FILE OPEN ERROR");
}
}
protected void onDestroy(){
super.onDestroy();
String inputTest = edit.getText().toString();
save(inputTest);
Log.d("123","FILE SAVE OK");
}
public void save(String inputTest) {
FileOutputStream out = null;
BufferedWriter writer = null;
try{
out = openFileOutput("caicai123.txt", Context.MODE_PRIVATE);
//out.getFD(
File filesDir = getFilesDir();
Log.d("123", filesDir.toString());
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputTest);
}catch (IOException e){
e.printStackTrace();
}
finally{
try {
if (writer != null) {
writer.close();
}
}catch(IOException e1){
e1.printStackTrace();
}
}
}
public String load(){
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try{
in = openFileInput("caicai123.txt");
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();
}
网友评论