1、利用文件存储
//将内容存在文件data内
public 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 (IOException e){
e.printStackTrace();
}
finally {
try{
if(writer!=null) {
writer.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
//从名为data的文件中加载内容
public String load(){
FileInputStream inputStream=null;
BufferedReader bufferedReader=null;
StringBuilder content=new StringBuilder();
try{
inputStream=openFileInput("data");
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while((line=bufferedReader.readLine())!=null){
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader!=null){
try{
bufferedReader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return content.toString();
}
2、SharedPreferences
//按下按键保存数据
{
Button saveData=(Button)findViewById(R.id.save_data);
Button restoreData=(Button)findViewById(R.id.restore_data);
saveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor=getSharedPreferences(
"data",MODE_PRIVATE).edit();
editor.putString("name","Tom");
editor.putInt("age",21);
editor.putBoolean("married",false);
editor.apply();
}
});
//按下按键读取数据在Log里显示
restoreData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences preferences=getSharedPreferences("data",MODE_PRIVATE);
String name=preferences.getString("name","");
int age=preferences.getInt("age",0);
boolean married=preferences.getBoolean(",married",false);
Log.d("MainActivity","name is "+name);
Log.d("MainActivity","age is "+age);
Log.d("MainActivity","married is "+married);
}
});
}