数据存储之openFileOutput()、openFileInput()
android studio 所生成的data文件在view –> tools window–> Device File Explorer
或者直接右下角Device File Explorer
找到/data/data/< package name>/files。百度上都含糊其辞。害我找半天也是醉了。
将数据存进文件和取出再存。
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit);
String inputTest = load();
if (!TextUtils.isEmpty(inputTest)) { //如果取得的数据不为空,就重新设置在此edit中
edit.setText(inputTest);
edit.setSelection(inputTest.length());
Toast.makeText(this, "Restoring", Toast.LENGTH_SHORT).show();
}
}
public String load() {
FileInputStream in = null;//读取数据
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line="";
if((line = reader.readLine())!=null){
content.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
@Override
protected void onDestroy() { //按返回键退出程序时
super.onDestroy();
String inputText = edit.getText().toString();//获取edit文本框中的值
try {
save(inputText);//保存下来
} catch (IOException e) {
e.printStackTrace();
}
}
public void save(String inputText) throws IOException {
FileOutputStream fileOutputStream = null;//保存数据
BufferedWriter bufferedWriter;
fileOutputStream = openFileOutput("data", MODE_PRIVATE);//会写到名为data文件夹中并覆盖。
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(inputText);
if (bufferedWriter != null) {
bufferedWriter.close();
}
}