Android 数据存储与读取:文件
|
admin
2013年2月25日 14:43
本文热度 4007
|
- 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);
-
- 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;
- }
-
- }
该文章在 2013/2/25 14:43:00 编辑过