Android讀寫SD卡,android讀寫sd

來源:互聯網
上載者:User

Android讀寫SD卡,android讀寫sd

  SD卡的讀寫是我們在開發Android 應用程式過程中最常見的操作。下面介紹SD卡的讀寫操作方式:

   1. 擷取SD卡的根目錄

String  sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();   // 何問起 hovertree.com

 2. 在SD卡上建立檔案夾目錄

/**  * 在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;  }  // 何問起 hovertree.com

 3. 在SD卡上建立檔案

/**  * 在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;  }  // 何問起 hovertree.com

4.判斷檔案是否存在於SD卡的某個目錄

/**  * 判斷SD卡上檔案是否存在  */  public boolean isFileExist(String fileName, String path)  {      File file = new File(sdCardRoot + path + File.separator + fileName);      return file.exists();  }  // 何問起 hovertree.com

  5.將資料寫入到SD卡指定目錄檔案

// 何問起 hovertree.com/* 寫入資料到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://www.cnblogs.com/roucheng/p/3504465.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.