This article describes the Android programming approach to writing data to SD cards. Share to everyone for your reference, specific as follows:
1. Code:
/**
* Write file to SDcard *
@param filename
* @param content file
/public
void Savetosdcard (String Filename,string content) throws exception{
file File=new file ("/mnt/sdcard", filename);
OutputStream out=new fileoutputstream (file);
Out.write (Content.getbytes ());
Out.close ();
}
SDcard corresponding file path: "/mnt/sdcard", do not write sdcard absolute path when developing, because the path will change because of the version change, here should use the following method to get SDcard path
For the previous code, modify the following code as follows:
/**
* Writes the file to the sdcard *
@param filename filename
* @param content file
/public void Savetosdcard ( String filename,string content) throws exception{
file File=new file (Environment.getexternalstoragedirectory (), filename);
OutputStream out=new fileoutputstream (file);
Out.write (Content.getbytes ());
Out.close ();
}
2. Get the right:
<!--permissions created in SDcard to delete files-->
<uses-permission <a href= "HTTP://LIB.CSDN.NET/BASE/15" class= Word "title=" undefined "target=" _blank "style=" Color:rgb (223, 52, 52); Font-weight:bold; " >android</a>:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!--the right to write data to SDcard- >
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
3. Judge the state of SDcard (SDcard may be write-protected or not inserted sdcard)
Save
String en=environment.getexternalstoragestate () to SDcard;
Gets the SDcard state if SDcard is plugged into the phone and is not write-protected state if
(En.equals (environment.media_mounted)) {
try {
Service.savetosdcard (filename, content);
Toast.maketext (Getapplicationcontext (), "Save Success", 1). Show ();
catch (Exception e) {
toast.maketext (Getapplicationcontext (), "Save Failed", 1). Show ();
}
else{
//Prompts the user SDcard does not exist or write-protected state
Toast.maketext (Getapplicationcontext (), "SDcard does not exist or write-protected state", 1). Show ();
For more information on Android-related content readers can view the site: "Android programming development of the SD card operation method Summary", "Android Development introduction and Advanced Course", "Android Resource Operation skills Summary", "Android View tips Summary" and "The Android Control usage Summary"
I hope this article will help you with the Android program.