一、步骤
二、简单实例
简单的备忘录:三个按钮(保存、读取、清空),一个编辑框。
public class MainActivity extends AppCompatActivity {
byte[] buffer = null; //定义保存数据的字节数组
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.Bn1);
Button button2 = findViewById(R.id.Bn2);
Button button3 = findViewById(R.id.Bn3);
EditText editText = findViewById(R.id.editText);
/****************************保存填写的memo信息***************************/
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String information = editText.getText().toString(); //获取输入的备忘信息
FileOutputStream fos = null; //声明文件输出流对象
try {
fos = openFileOutput("memo",MODE_PRIVATE); //获取文件输出流对象,第一个参数为文件名。
fos.write(information.getBytes()); //保存备忘信息(要求读取以字节数组保存的数据)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos!=null) {
try {
fos.close(); //关闭文件输出流
Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
/****************************读取填写的memo信息***************************/
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FileInputStream fis = null; //声明文件输入流对象
try{
fis = openFileInput("memo"); //获取文件输出流对象
buffer = new byte[fis.available()]; //实例化保存数据的字节数组
fis.read(buffer); //从输入流读取数据
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close(); //关闭输入流对象
String information = new String(buffer); //把字符数组中的数据转换成字符串
editText.setText(information);
Toast.makeText(MainActivity.this, "读取成功", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
/**************清空文本*************/
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editText.getText().toString().length()!=0){
editText.setText(""); //清空文本
Toast.makeText(MainActivity.this, "已清空", Toast.LENGTH_SHORT).show();
}
}
});
}
}