Android中的数据存取(二)File
File的存取方法适用于将数据直接以文本的形式保存在设备之中,通过Context.openFileInput()方法获得标准Java文件输入流(FileInputStream),通过Context.openFileOutput()方法获得标准Java文件输出流(FileOutputStream)
下面是具体代码
package com.example.data2; import java.io.FileInputStream; import java.io.FileOutputStream; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText write,read; Button writeb,readb; private static final String File_name="data2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creatView(); setlistener1(); setlistener2(); } private void setlistener2() { // TODO Auto-generated method stub readb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub read.setText(read()); } }); } private void setlistener1() { // TODO Auto-generated method stub writeb.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub write(write.getText().toString()); } }); } private void creatView() { // TODO Auto-generated method stub write=(EditText)findViewById(R.id.write); read=(EditText)findViewById(R.id.read); writeb=(Button)findViewById(R.id.writeb); readb=(Button)findViewById(R.id.readb); } private String read(){ try { FileInputStream datain=openFileInput(File_name); byte[] buffer=new byte[datain.available()]; datain.read(buffer); return new String(buffer); } catch (Exception e){ e.printStackTrace(); } return null; } private void write(String content){ try{ FileOutputStream dataout=openFileOutput(File_name, MODE_APPEND); dataout.write(content.getBytes()); dataout.close(); }catch (Exception e){ e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
测试完成