Public classSdcardtest extends activity{final String file_name="/crazyit.bin"; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); //get two buttonsButton Read =(Button) Findviewbyid (R.id.read); Button Write=(Button) Findviewbyid (r.id.write); //get two text boxesFinal EditText edit1 =(EditText) Findviewbyid (R.ID.EDIT1); Final EditText Edit2=(EditText) Findviewbyid (R.ID.EDIT2); //to bind an event listener to the Write buttonWrite.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View source) {//writing content from Edit1 to a fileWrite (Edit1.gettext (). toString ()); Edit1.settext (""); } }); Read.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//reads the contents of the specified file and displays itEdit2.settext (read ()); } }); } PrivateString Read () {Try { //if the phone is plugged into an SD card and the app has access to SD if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { //get the storage directory for the SD cardFile Sdcarddir =environment.getexternalstoragedirectory (); //gets the input stream corresponding to the specified fileFileInputStream FIS =NewFileInputStream (Sdcarddir.getcanonicalpath ()+file_name); //wraps the specified input stream into BufferedReaderBufferedReader br =NewBufferedReader (NewInputStreamReader (FIS)); StringBuilder SB=NewStringBuilder (""); String Line=NULL; //looping through the contents of a file while(line = Br.readline ())! =NULL) {sb.append (line); } //Close ResourceBr.close (); returnsb.tostring (); } } Catch(Exception e) {e.printstacktrace (); } return NULL; } Private voidWrite (String content) {Try { //if the phone is plugged into an SD card and the app has access to SD if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { //get the SD card directoryFile Sdcarddir =environment.getexternalstoragedirectory (); File TargetFile=NewFile (Sdcarddir. Getcanonicalpath ()+file_name); //Create a Randomaccessfile object with the specified fileRandomaccessfile RAF =Newrandomaccessfile (TargetFile,"RW"); //move the file record pointer to the lastRaf.seek (Targetfile.length ()); //Output File ContentsRaf.write (Content.getbytes ()); //Close RandomaccessfileRaf.close (); } } Catch(Exception e) {e.printstacktrace (); } }}
Android read SD card file