文件保存
package com.example.datastroredtest; import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText; import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter; public class MainActivity extends Activity { EditText username = null;
EditText password = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password); } @Override
protected void onDestroy() {
super.onDestroy();
String fileName ="data";
String user_name = username.getText().toString();
String pass_word = password.getText().toString();
save(fileName,user_name,pass_word);
} public void save(String fileName, String username, String password) { FileOutputStream fos = null;
BufferedWriter writer = null;
try{
fos = openFileOutput(fileName,MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write("<username>");
writer.write(username);
writer.write("</username>");
writer.write("\n");
writer.write("<password>");
writer.write(password);
writer.write("</password>"); }catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer != null){
writer.close();
}
}catch (IOException e){
e.printStackTrace();
}
} }
}
package com.example.datastroredtest; import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText; import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList; public class MainActivity extends Activity { EditText username = null;
EditText password = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password); } @Override
protected void onDestroy() {
super.onDestroy();
String fileName ="data";
ArrayList<String> values = load(fileName);
username.setText(values.get(0));
password.setText(values.get(1));
} public ArrayList<String> load(String fileName) { FileInputStream fis = null;
BufferedReader reader = null;
ArrayList<String> content = new ArrayList<String>(); try{
fis = openFileInput(fileName);
reader = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = reader.readLine()) != null){
content.add(line);
} }catch (IOException e){
e.printStackTrace();
}finally {
try{
if(reader != null){
reader.close();
}
}catch (IOException e){
e.printStackTrace();
}
} return content;
}
}