android openFileInput openFileOutput



openFileInput  打开应用程序的数据文件夹下的name文件对应的输入流

openFileOutput打开应用程序的数据文件夹下的name文件对应的输出流


下面是读写的例子

public class MainActivity extends Activity {

 private EditText et1;
 private EditText et2;
 private Button bt1;
 private Button bt2;
 final String FILE_NAME = "crazyit.bin";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  et1 = (EditText) findViewById(R.id.editText1);
  et2 = (EditText) findViewById(R.id.editText2);
  bt1 = (Button) findViewById(R.id.button1);
  bt2 = (Button) findViewById(R.id.button2);
  bt1.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    write(et1.getText().toString());
    et1.setText("");
   }
  });
  bt2.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    et2.setText(read());
   }
  });

 }

 private String read(){
  
  try {
   FileInputStream fis = openFileInput(FILE_NAME);
   byte[] buff = new byte[1024];
   int hasread = 0;
   StringBuilder sb = new StringBuilder();
   while((hasread=fis.read(buff))>0){
    sb.append(new String(buff,0,hasread));
   }
   fis.close();
   return sb.toString();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null ;
 }
 
 private void write(String content){
  
  try {
   FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
   PrintStream ps = new PrintStream(fos);
   ps.println(content);
   ps.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }
 
 
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。