文件存储的核心是Context提供了一个openFileOutput()与openFileInput()俩个方法

课程demo

 public class MainActivity extends AppCompatActivity {
private EditText edit;
private TextView tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= (EditText) findViewById(R.id.edit);
tx= (TextView) findViewById(R.id.tx);
}
@Override
protected void onDestroy() {
super.onDestroy();
String input=edit.getText().toString();
save(input);
}
//保存数据
思想:通过openFileOutput方法,得到一个FileOutputStream对象,将其包裹在
OutputStreamWriter上,也生成一个对象,继续包裹在BufferedWriter上,得到一个对象
调用write()方法,把数据传入
  private void save(String input) {
FileOutputStream fileout=null;
BufferedWriter writer=null;
try {
//data:文件名 Context.MODE_PRIVATE:访问权限
fileout=openFileOutput("data", Context.MODE_PRIVATE);
writer=new BufferedWriter(new OutputStreamWriter(fileout));
writer.write(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(writer!=null)
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void doclick(View v) {
switch (v.getId()) {
case R.id.bt:
String text = load();
tx.setText(text);
}
}
//取出数据
public String load()
{
FileInputStream input=null;
BufferedReader read=null;
//StringBuilder的对象的append方法可以将字符连接起来
StringBuilder content=new StringBuilder();
try {
input=openFileInput("data");
read=new BufferedReader(new InputStreamReader(input));
String line="";
while((line=read.readLine())!=null){
content.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
05-11 18:18