android 读写SD卡上的文件

首先增加权限

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


主要的activity

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 {
   if (Environment.getExternalStorageState().equals(
     Environment.MEDIA_MOUNTED)) {
    File sdcardDir = Environment.getExternalStorageDirectory();
    FileInputStream fis = openFileInput(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;
 }

 private void write(String content) {
  try {
   if (Environment.getExternalStorageState().equals(
     Environment.MEDIA_MOUNTED)) {
    File sdcardDir = Environment.getExternalStorageDirectory();
    File targetFile = new File(sdcardDir.getAbsoluteFile()
      .getCanonicalPath() + FILE_NAME);
    RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
    raf.seek(targetFile.length());
    raf.write(content.getBytes());
    raf.close();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值