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
String sdcardroot = environment.getexternalstoragedirectory (). GetAbsolutePath (); // how to ask Hovertree.com
2. Create a folder directory on the SD card
/** * Create directory on SD card * /Public File Createdironsdcard (String dir) { New File (sdcardroot + file.separator + dir +file.separator); LOG.V ("Createdironsdcard", Sdcardroot + file.separator + dir +file.separator); Dirfile.mkdirs (); return dirfile; } // how to ask Hovertree.com
3. Create a file on the SD card
/** * create file on SD card */public throws ioexception { New File (sdcardroot + file.separator + dir + file.separator + fileName); LOG.V ("Createfileonsdcard", Sdcardroot + file.separator + dir + file.separator + fileName); File.createnewfile (); return file; } // how to ask Hovertree.com
4. Determine if the file exists in a directory on the SD card
/** * Determine if the file on the SD card exists * /Publicboolean isfileexist (String fileName, String path) { new File (sdcardroot + path + file.separator + fileName); return file.exists (); } // how to ask Hovertree.com
5. Write the data to the SD card specified directory file
//how to ask Hovertree.com/*write data to sd card*/ Publicfile Writedata2sdcard (string path, string fileName, InputStream data) {File file=NULL; OutputStream Output=NULL; Try{createdironsdcard (path); //Create a directoryFile = Createfileonsdcard (fileName, path);//Create a fileOutput =Newfileoutputstream (file); byteBuffer[] =New byte[2*1024];//Write 2K data every time inttemp; 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 (); } } returnfile; }
One more important thing:
to operate the SD card, you must apply for permission:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
Recommendation: http://www.cnblogs.com/roucheng/p/3504465.html
Android read/write SD card