The Method of Writing Data to SD Card by Android Programming
- 2021-07-01 08:12:07
- OfStack
In this paper, an example is given to describe the method of writing data to SD card by Android programming. Share it for your reference, as follows:
1. Code:
/**
* Toward sdcard Write a file in
* @param filename Filename
* @param content File content
*/
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();
}
File path corresponding to sdcard: "/mnt/sdcard". Do not write the absolute path of SDCard when developing, because the path will change due to the change of version. Here, you should use the following methods to obtain the path of SDCard
Modify the following code corresponding to the above 1 code as follows:
/**
* Toward sdcard Write a file in
* @param filename Filename
* @param content File content
*/
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. Access:
<!-- In SDCard Permissions created in delete files in -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- To SDCard Permissions to write data in -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3. Determine the SDCard state (SDCard may be write-protected, or SDCard may not be inserted)
// Toward SDCard Save in
String en=Environment.getExternalStorageState();
// Get SDCard Status , If SDCard The phone is plugged in and is not write-protected
if(en.equals(Environment.MEDIA_MOUNTED)){
try {
service.saveToSDCard(filename, content);
Toast.makeText(getApplicationContext(), " Save successfully ", 1).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), " Save failed ", 1).show();
}
}else{
// Prompt the user SDCard Does not exist or is write-protected
Toast.makeText(getApplicationContext(), "SDCard Does not exist or is write-protected ", 1).show();
}
For more readers interested in Android related content, please check the topics on this site: "Summary of SD Card Operation Methods for Android Programming Development", "Introduction and Advanced Tutorial for Android Development", "Summary of Android Resource Operation Skills", "Summary of View Skills for Android View" and "Summary of Android Control Usage"
I hope this article is helpful to everyone's Android programming.