package com.nguhyw.sdcard;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edit;
private TextView show;
private Button writebnt;
private Button readbnt;
byte[] buff1 = new byte[10];
char[] buff2 = new char[10];
File sdcard = Environment.getExternalStorageDirectory();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.editText);
show = (TextView) findViewById(R.id.show);
writebnt = (Button) findViewById(R.id.writebnt);
readbnt = (Button) findViewById(R.id.readbnt);
writebnt.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
File myfile = new File(sdcard,"Temple.fptH");
if(!sdcard.exists()){
Toast.makeText(getApplicationContext(), "当前系统不具备SD卡", Toast.LENGTH_SHORT).show();
return ;
}
for(int i=0;i<10;i++){buff1[i]=0x38;buff2[i]=(char) buff1[i];}
try {
myfile.createNewFile();
Toast.makeText(getApplicationContext(), "文件创建完成", Toast.LENGTH_SHORT).show();
FileOutputStream fos = new FileOutputStream(myfile);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(buff2);
osw.flush();
osw.close();
fos.close();
Toast.makeText(getApplicationContext(), "数据写入完成", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
readbnt.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
File myfile = new File(sdcard,"Temple.fptH");
if(myfile.exists()){
try {
FileInputStream fis =new FileInputStream(myfile);
InputStreamReader isr =new InputStreamReader(fis);
char[] input = new char[fis.available()];
isr.read(input);
isr.close();
fis.close();
String str = new String(input);
show.setText(str);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
第四步设置应用的权限: