Copy Code code as follows:
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)) {
Get the directory of the SD card
File Sdcarddir = Environment.getexternalstoragedirectory ();
File TargetFile = new file (Sdcarddir.getcanonicalpath () + file_name);
Creates a Randomaccessfile object with the specified file
Randomaccessfile RAF = new Randomaccessfile (targetfile, "RW");
Move the file record pointer to the last
Raf.seek (Targetfile.length ());
Output file contents
Raf.write (Content.getbytes ());
Raf.close ();
}
catch (Exception e) {
E.printstacktrace ();
}
}
Private String Read () {
try {
if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
Obtain the corresponding storage directory of SD card
File Sdcarddir = Environment.getexternalstoragedirectory ();
Gets the input stream corresponding to the specified file
FileInputStream fis = new FileInputStream (Sdcarddir.getcanonicalpath () + file_name);
Wraps the specified input stream into a bufferreader
BufferedReader br = new BufferedReader (new InputStreamReader (FIS));
StringBuilder sb = new StringBuilder ("");
String line = null;
Iterate over the contents of a file
while (line = Br.readline ())!= null) {
Sb.append (line);
}
Br.close ();
return sb.tostring ();
}
catch (Exception e) {
E.printstacktrace ();
}
return null;
}
}
Finally, don't forget to increase access to read SD in Androidmanafest.xml.