packagecom.example.cheng.myapplication;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Environment;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.TextView;importandroid.widget.Toast;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.UnsupportedEncodingException;publicclassTestActivityextendsActivity{privateStringfileName="test";privateEditTexteditText;privateTextViewshow;privateButtonwriteButton;privateButtonreadButton;Filesdcard=Environment.getExternalStorageDirectory();@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_test);editText=(EditText)findViewById(R.id.editText);show=(TextView)findViewById(R.id.show);readButton=(Button)findViewById(R.id.readBtn);writeButton=(Button)findViewById(R.id.writeBtn);writeButton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){FilemyFile=newFile(sdcard,"This is my File.txt");if(!sdcard.exists()){//判断是否存在sd卡Toast.makeText(getApplicationContext(),"当前系统不具备SD卡目录",Toast.LENGTH_SHORT).show();return;}try{myFile.createNewFile();Toast.makeText(getApplicationContext(),"文件已经创建完成!",Toast.LENGTH_SHORT).show();FileOutputStreamfos=newFileOutputStream(myFile);OutputStreamWriterosw=newOutputStreamWriter(fos);osw.write(editText.getText().toString());osw.flush();osw.close();fos.close();Toast.makeText(getApplicationContext(),"文件已经写入完成!",Toast.LENGTH_SHORT).show();}catch(IOExceptione){e.printStackTrace();}}});readButton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){FilemyFile=newFile(sdcard,"This is my File.txt");if(sdcard.exists()){//判断是否存在sd卡try{FileInputStreamfis=newFileInputStream(myFile);InputStreamReaderisr=newInputStreamReader(fis,"UTF-8");char[]input=newchar[fis.available()];isr.read(input);isr.close();fis.close();Stringstr=newString(input);show.setText(str);}catch(FileNotFoundExceptione){e.printStackTrace();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}}});}}