標籤:
SD卡的讀寫是我們在開發android 應用程式過程中最常見的操作。下面介紹SD卡的讀寫操作方式:
1. 擷取SD卡的根目錄
[java] view plaincopy
- String sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
2. 在SD卡上建立檔案夾目錄
[java] view plaincopy
- /**
- * 在SD卡上建立目錄
- */
- 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. 在SD卡上建立檔案
[java] view plaincopy
- /**
- * 在SD卡上建立檔案
- */
- 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.判斷檔案是否存在於SD卡的某個目錄
[java] view plaincopy
- /**
- * 判斷SD卡上檔案是否存在
- */
- public boolean isFileExist(String fileName, String path)
- {
- File file = new File(sdCardRoot + path + File.separator + fileName);
- return file.exists();
- }
5.將資料寫入到SD卡指定目錄檔案
[java] view plaincopy
- <span style="white-space:pre"> </span>/**
- * 寫入資料到SD卡中
- */
- public File writeData2SDCard(String path, String fileName, InputStream data)
- {
- File file = null;
- OutputStream output = null;
-
- try {
- createDirOnSDCard(path); //建立目錄
- file = createFileOnSDCard(fileName, path); //建立檔案
- output = new FileOutputStream(file);
- byte buffer[] = new byte[2*1024]; //每次寫2K資料
- int temp;
- while((temp = data.read(buffer)) != -1 )
- {
- output.write(buffer,0,temp);
- }
- output.flush();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally{
- try {
- output.close(); //關閉資料流操作
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
-
- return file;
- }
one more important thing:
對SD卡的操作,必須要申請許可權:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
轉自:http://blog.csdn.net/newjerryj/article/details/8829179
Android入門開發之SD卡讀寫操作(轉)