package com.example.sdcardtest; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { final String FILE_NAME = "/baidu/hello.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button read = (Button) findViewById(R.id.read); Button write = (Button) findViewById(R.id.write); final EditText edit1 = (EditText) findViewById(R.id.editText1); final EditText edit2 = (EditText) findViewById(R.id.editText2); //为write事件绑定监听器 write.setOnClickListener(new OnClickListener() { public void onClick(View v) { write(edit1.getText().toString()); edit1.setText(""); } }); //为read事件绑定监听器 read.setOnClickListener(new OnClickListener() { public void onClick(View v) { edit2.setText(read()); } }); } public String read(){ if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File sdCardDir = Environment.getExternalStorageDirectory(); try { FileInputStream fis = new FileInputStream(sdCardDir.getCanonicalPath() + FILE_NAME); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); StringBuilder sb = new StringBuilder(""); String line = null; while( (line = br.readLine()) != null ){ sb.append(line); } br.close(); return sb.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } public void write(String content){ if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ RandomAccessFile raf = null; try { //获取sd卡的目录 File sdCardDir = Environment.getExternalStorageDirectory(); File targetFile = new File(sdCardDir.getCanonicalFile() + FILE_NAME); raf = new RandomAccessFile(targetFile, "rw"); raf.seek(targetFile.length()); raf.write(content.getBytes()); } catch (IOException e) { e.printStackTrace(); } try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } ===================== 布局文件 简单的两个按钮,没什么好说的