Android read/write sd card, android read/write sd
SD card read/write is the most common operation in the Development of Android applications. The following describes how to read and write SD cards:
1. Get the root directory of the SD card
String sdCardRoot = Environment. getExternalStorageDirectory (). getAbsolutePath (); // He asked hovertree.com
2. Create a folder directory on the SD card
/*** Create directory on 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;} // hovertree.com
3. Create a file on the SD card
/*** 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;} // hovertree.com
4. Determine whether the file exists in a directory on the SD card
/*** Determine whether the File on the SD card exists */public boolean isFileExist (String fileName, String path) {file File = new File (sdCardRoot + path + File. separator + fileName); return file. exists ();} // He asked hovertree.com
5. Write Data to the specified directory file on the SD card
// Why? hovertree.com/* write data to the 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 a file output = new FileOutputStream (file ); byte buffer [] = new byte [2*1024]; // each write 2 k data int temp; while (temp = data. read (buffer ))! =-1) {output. write (buffer, 0, temp);} output. flush ();} catch (Exception e) {e. printStackTrace ();} finally {try {output. close (); // close the data stream operation} catch (Exception e2) {e2.printStackTrace () ;}} return file ;}
One more important thing:
To perform operations on the SD card, you must apply for the following permissions:
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>
Recommended: http://www.cnblogs.com/roucheng/p/3504465.html