Android文件保存和读取
16lz
2021-12-04
- publicclassDataActivityextendsActivity{
- privateEditTextfilenameText;
- privateEditTextcontentText;
- privateTextViewresultView;
- privatestaticfinalStringTAG="DataActivity";
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- filenameText=(EditText)this.findViewById(R.id.filename);
- contentText=(EditText)this.findViewById(R.id.content);
- resultView=(TextView)this.findViewById(R.id.result);
- Stringfilename=filenameText.getText().toString();
- Buttonbutton=(Button)this.findViewById(R.id.button);
- ButtonshowButton=(Button)this.findViewById(R.id.showButton);
- button.setOnClickListener(listener);
- showButton.setOnClickListener(listener);
- }
- privateView.OnClickListenerlistener=newView.OnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- Buttonbutton=(Button)v;
- Stringfilename=filenameText.getText().toString();
- switch(button.getId()){
- caseR.id.button://如果是保存按钮
- intresId=R.string.success;
- Stringcontent=contentText.getText().toString();
- try{
- OutputStreamoutStream=DataActivity.this.openFileOutput(filename,Context.MODE_WORLD_WRITEABLE+Context.MODE_WORLD_READABLE);
- //四中操作模式
- //Context.MODE_PRIVATE=0覆盖、私有
- //Context.MODE_APPEND=32768追加、私有
- //Context.MODE_WORLD_READABLE=1其他的程序可以访问
- //Context.MODE_WORLD_WRITEABLE=2
- try{
- FileService.save(outStream,content);//保存文件
- }catch(Exceptione){
- Log.e(TAG,e.toString());
- resId=R.string.error;
- }
- }catch(FileNotFoundExceptione){
- Log.e(TAG,e.toString());
- resId=R.string.error;
- }
- Toast.makeText(DataActivity.this,resId,Toast.LENGTH_LONG).show();
- break;
- caseR.id.showButton://如果是显示按钮
- try{
- InputStreaminStream=DataActivity.this.openFileInput(filename);
- Stringtext=FileService.read(inStream);
- resultView.setText(text);
- }catch(Exceptione){
- Log.e(TAG,e.toString());
- resId=R.string.error;
- Toast.makeText(DataActivity.this,"读取失败",Toast.LENGTH_LONG).show();
- }
- break;
- }
- }
- };
- }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/702531
更多相关文章
- Android自定义对话框的使用
- Android自定义对话框的使用
- Android自定义对话框的使用
- 小编程(三):用户登录注册界面开发及用户信息管理案例代码详解
- 我的Android进阶之旅------>Android视频录制小例子
- Android回调——Android模块化编程
- Android修行之路——Dialog
- Android(安卓)按钮添加单击事件
- Android官方入门文档[6]添加Action按钮