首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

Android 数据储存与读取:文件

2012-09-09 
Android 数据存储与读取:文件public class MainActivity extends Activity implements View.OnClickListen

Android 数据存储与读取:文件

Android 数据储存与读取:文件

public class MainActivity extends Activity implements View.OnClickListener{Button btnSave;Button btnRead;EditText edFileName;EditText edFileContent;String fileName;String fileContent;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // 获取页面中的组件        btnSave=(Button) findViewById(R.id.btnSave);        btnRead=(Button) findViewById(R.id.btnRead);        //添加按钮监听        btnSave.setOnClickListener(this);        btnRead.setOnClickListener(this);    }    public void onClick(View v) {edFileName=(EditText) findViewById(R.id.edFileName);edFileContent=(EditText) findViewById(R.id.edContent);fileName=edFileName.getText().toString();fileContent=edFileContent.getText().toString();switch (v.getId()) {    case R.id.btnSave:    save(fileName,fileContent);    Toast.makeText(getApplicationContext(), "保存成功!", 1).show();    break;    case R.id.btnRead:    edFileContent.setText(read(fileName));    break;} }public void save(String fileName, String fileContent) {try {//创建输出流,模式为私有模式,只能被本应用访问,FileOutputStream outStream = getApplicationContext().openFileOutput(fileName, MODE_PRIVATE);//默认会保存到 /data/data/package name/files下,如果不存在则会创建,outStream.write(fileContent.getBytes());outStream.close();} catch (Exception e) {e.printStackTrace();}}public String read(String fileName)  {FileInputStream inputStream;try {inputStream = getApplicationContext().openFileInput(fileName);ByteArrayOutputStream outStream =new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=0;while((len=inputStream.read(buffer))!=-1){outStream.write(buffer, 0, len);}byte[] data=outStream.toByteArray();inputStream.close();outStream.close();return new String(data);} catch (Exception e) {e.printStackTrace();}return null;}}


热点排行