public class MainActivity extends Activity implementsOnClickListener {privateButton fileSave;privateButton fileRead;privateButton picSave;privateButton picRead;privateImageView iv;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileSave=(Button) findViewById(R.id.button1);
fileRead=(Button) findViewById(R.id.button2);
picSave=(Button) findViewById(R.id.button3);
picRead=(Button) findViewById(R.id.button4);
iv=(ImageView) findViewById(R.id.imageView1);
fileSave.setOnClickListener(this);
fileRead.setOnClickListener(this);
picSave.setOnClickListener(this);
picRead.setOnClickListener(this);
}
@Overridepublic voidonClick(View v) {int id =v.getId();switch(id) {caseR.id.button1:
FileOutputStream saveTxt= null;//获取外存储卡状态
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File dir=Environment.getExternalStorageDirectory();//存储一个文本文件
File file = new File(dir, "cc.txt");try{
saveTxt= newFileOutputStream(file);
saveTxt.write("i am cc!!".getBytes());
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{if (saveTxt != null) {try{
saveTxt.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}break;caseR.id.button2://读取外存文件
FileInputStream fis = null;if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File dir=Environment.getExternalStorageDirectory();
File file= new File(dir, "cc.txt");try{
fis= newFileInputStream(file);byte[] b = new byte[1024];int len = 0;
StringBuilder sb= newStringBuilder();while ((len = fis.read(b)) != -1) {
String string= new String(b, 0, len);
sb.append(string);
}
Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{if (fis != null) {try{
fis.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}break;caseR.id.button3://把图片存入外存
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Bitmap bm=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File dir=Environment.getExternalStorageDirectory();
File file= new File(dir, "cc.jpg");
FileOutputStream fos= null;try{
fos= newFileOutputStream(file);
bm.compress(CompressFormat.JPEG,100, fos);
}catch(FileNotFoundException e) {
e.printStackTrace();
}finally{if (fos != null) {try{
fos.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}break;caseR.id.button4://从外存读取图片
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File dir=Environment.getExternalStorageDirectory();
File file= new File(dir, "cc.jpg");
Bitmap bm=BitmapFactory.decodeFile(file.getPath());
iv.setImageBitmap(bm);
}break;default:break;
}
}
}