Android(安卓)数据存储与读取:文件
16lz
2022-01-21
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;}}
更多相关文章
- MacAndroid源码下载 Android10详解
- android中Json数据保存方式
- Android(安卓)Base64编码
- Android(安卓)深色模式适配
- Android应用程序资源管理器(Asset Manager)的创建过程分析
- Android和设计模式:代理模式
- Android是否可以实现静默安装模式
- android的文件操作
- 年后面试,差点就痛失了字节跳动Android岗的Offer,原因竟是因为性能