Android儲存HashMap到File裡
2017-10-05 本文已影响0人
Derrick_Chung
儲存
private void saveData() {
FileOutputStream outputStream;
try {
HashMap<String,String> map = new HashMap<>();
map.put(NAME, edtName.getText().toString());
map.put(AGE , edtAge.getText().toString());
outputStream = getActivity().openFileOutput(filename , Context.MODE_PRIVATE);
ObjectOutput out = new ObjectOutputStream(outputStream);
out.writeObject(map);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
讀資料
private void loadData(){
try {
FileInputStream fileIn = getActivity().openFileInput(filename);
if(fileIn != null){
ObjectInputStream in = new ObjectInputStream(fileIn);
HashMap<String,String> map = (HashMap<String, String>) in.readObject();
edtName.setText(map.get(NAME));
edtAge.setText(map.get(AGE));
}
} catch (Exception e) {
e.printStackTrace();
}
}