应用场景:离开登录页面保存账号
1、在onCreate方法中提取保存数据,即给账号输入框赋值
etPhone.setText(DataUtils.loadData(this));
2、在onDestroy方法中保存账号
String phone = etPhone.getText().toString();
DataUtils.saveData(this, phone);
3、工具类(数据保存方法和提取方法)
public class DataUtils {
/**
* 保存数据
* @param context
* @param str
*/
public static void saveData(Context context, String str) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = context.openFileOutput("phone", Context.MODE_PRIVATE);//phone:文件名;MODE_PRIVATE:同文件名覆盖;MODE_APPEND:同文件名添加
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(str);
} catch (IOException e){
e.printStackTrace();
} finally {
try {
if (writer != null){
writer.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
/**
* 提取数据
* @param context
*/
public static String loadData(Context context) {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder str = new StringBuilder();
try {
in = context.openFileInput("phone");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null){
str.append(line);
}
} catch (IOException e){
e.printStackTrace();
} finally {
try {
if (reader != null){
reader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return str.toString();
}
}
????????上面单个字段的存储一般使用SharedPreferences来保存数据,这种文件存储可以适用于网络json数据的本地保存,提交表单数据的临时保存等。
|