目录
MainActivity:
package com.example.administrator.myapplication;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etinfo;
private Button btnSave;
private Button btnRead;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etinfo=(EditText)findViewById(R.id.et_info);
btnSave=(Button)findViewById(R.id.btn_save);
btnRead=(Button)findViewById(R.id.btn_read);
btnSave.setOnClickListener(this);
btnRead.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.btn_save:
String saveInfo = etinfo.getText().toString().trim();
FileOutputStream fos;
try{
fos=openFileOutput("data.txt",MODE_APPEND);
fos.write(saveInfo.getBytes());
fos.close();
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(MainActivity.this,"数据保存成功",Toast.LENGTH_SHORT).show();
break;
case R.id.btn_read:
String content="";
try{
FileInputStream fin=openFileInput("data.txt");
byte[]buffer= new byte[ fin.available()];
fin.read(buffer);
content=new String(buffer);
fin.close();
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(MainActivity.this,"The Data is:",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
activity_main.xml: