The reading and writing of SD cards is the most common operation we have in the process of developing Android applications. The following describes how the SD card reads and writes:
1. Get the root directory of the SD card
[Java]View Plaincopy
- String sdcardroot = Environment.getexternalstoragedirectory (). GetAbsolutePath ();
2. Create a folder directory on the SD card
[Java]View Plaincopy
- /**
- * Create a directory on the SD card
- */
- Public File Createdironsdcard (String dir)
- {
- File Dirfile = new File (sdcardroot + file.separator + dir +file.separator);
- LOG.V ("Createdironsdcard", Sdcardroot + file.separator + dir +file.separator);
- Dirfile.mkdirs ();
- return dirfile;
- }
3. Create a file on the SD card
[Java]View Plaincopy
- /**
- * Create a file on the SD card
- */
- Public File Createfileonsdcard (string fileName, String dir) throws IOException
- {
- File File = new file (sdcardroot + file.separator + dir + file.separator + fileName);
- LOG.V ("Createfileonsdcard", Sdcardroot + file.separator + dir + file.separator + fileName);
- File.createnewfile ();
- return file;
- }
4. Determine if the file exists in a directory on the SD card
[Java]View Plaincopy < param name= "allowfullscreen" value= "false" >< param name= "wmode" value= "Transparent" >
- /**
- * Determine if the file exists on the SD card
- */
- Public Boolean isfileexist (String fileName, string path)
- {
- File File = new file (sdcardroot + path + file.separator + fileName);
- return file.exists ();
- }
5. Write the data to the SD card specified directory file
[Java]View Plaincopy
- <span style="White-space:pre" > </span>/**
- * Write data to SD card
- */
- Public File Writedata2sdcard (string path, string fileName, InputStream data)
- {
- File file = null;
- OutputStream output = null;
- try {
- Createdironsdcard (path); //Create a directory
- File = Createfileonsdcard (fileName, path); //Create file
- Output = new FileOutputStream (file);
- byte buffer[] = new byte[1024]; //write 2K data each time
- int temp;
- While (temp = data.read (buffer))! =-1)
- {
- Output.write (buffer,0,temp);
- }
- Output.flush ();
- } catch (Exception e) {
- E.printstacktrace ();
- }
- finally{
- try {
- Output.close (); //Turn off Data flow operations
- } catch (Exception E2) {
- E2.printstacktrace ();
- }
- }
- return file;
- }
One more important thing:
to operate the SD card, you must apply for permission:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
Transferred from: http://blog.csdn.net/newjerryj/article/details/8829179
Android Entry Development SD card read and write operation (GO)