android读写sd卡操作写入数据读取数据示例
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.os.bundle;
import android.os.environment;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.edittext;
import android.app.activity;
public class mainactivity extends activity {
final string file_name = "/lxp.bin";
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
button write = (button) findviewbyid(r.id.main_btn1);
button read = (button) findviewbyid(r.id.main_btn2);
final edittext edit1 = (edittext) findviewbyid(r.id.main_edit1);
final edittext edit2 = (edittext) findviewbyid(r.id.main_edit2);
write.setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
write(edit1.gettext().tostring().trim());
edit1.settext("");
}
});
read.setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
edit2.settext(read());
}
});
}
private void write(string content){
try {
if(environment.getexternalstoragestate().equals(environment.media_mounted)){
//获取sd卡的目录
file sdcarddir = environment.getexternalstoragedirectory();
file targetfile = new file(sdcarddir.getcanonicalpath() + file_name);
//以指定文件创建randomaccessfile对象
randomaccessfile raf = new randomaccessfile(targetfile, "rw");
//将文件记录指针移动到最后
raf.seek(targetfile.length());
//输出文件内容
raf.write(content.getbytes());
raf.close();
}
} catch (exception e) {
e.printstacktrace();
}
}
private string read(){
try {
if(environment.getexternalstoragestate().equals(environment.media_mounted)){
//获得sd卡对应的存储目录
file sdcarddir = environment.getexternalstoragedirectory();
//获取指定文件对应的输入流
fileinputstream fis = new fileinputstream(sdcarddir.getcanonicalpath() + file_name);
//将指定输入流包装成bufferreader
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 (exception e) {
e.printstacktrace();
}
return null;
}
}
最后别忘了在androidmanafest.xml中增加访问读取sd的权限。