標籤:
android提供對可移除的外部儲存進行檔案儲存體。在對外部sdcard進行調用的時候首先要調用Environment.getExternalStorageState()檢查sdcard的可用狀態。通過Environment.getExternalStorageDirectory()得到Sdcard的路徑。檔案寫入外部儲存需要添加對sdcard的授權
<!-- 寫sdcard需要添加寫sdcard的授權 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
android學習過程中的樣本如下:
檔案讀寫工具類:
1 package com.example.android_data_storage_sdcard.file; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 import android.os.Environment; 9 import android.util.Log;10 /**11 * @author xiaowu12 * @note 檔案儲存體之外部儲存(sdcard儲存)。13 * 外部儲存不需要context 14 */15 public class FileUitls {16 private final String TAG = "FileUtil";17 18 /**19 * 儲存檔案至外部儲存的SD卡20 * 21 * @param fileName22 * @param mode23 * @param data24 * @return25 */26 public boolean saveFileToSdcard(String fileName, byte[] data) {27 boolean flag = false;28 // 判斷sdcard的狀態29 String state = Environment.getExternalStorageState();30 // 擷取sdcard的根目錄 /mnt/sdcard/...31 File root = Environment.getExternalStorageDirectory();32 FileOutputStream outputStream = null;33 // Environment.MEDIA_MOUNTED表示SD卡掛載在手機上並可以讀寫34 if (Environment.MEDIA_MOUNTED.equals(state)) {35 // 在sdcard的根目錄下建立檔案36 File file = new File(root, fileName);37 try {38 outputStream = new FileOutputStream(file);39 outputStream.write(data, 0, data.length);40 flag = true ;41 } catch (FileNotFoundException e) {42 Log.i(TAG, "檔案未找到異常!");43 } catch (Exception e) {44 Log.i(TAG, "寫檔案發生異常");45 } finally {46 if (outputStream != null) {47 try {48 outputStream.close();49 } catch (IOException e) {50 Log.i(TAG, "關閉IO流發生異常!");51 }52 }53 }54 }55 return flag;56 }57 }
Junit單元測試類:
單元測試類必須繼承自AndroidTestCase,並在資源資訊清單檔中添加單元測試包 <uses-library android:name="android.test.runner"/>,並添加單元測試目標包
<!-- 引入單元測試目標包 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.android_data_storage_sdcard" >
</instrumentation>
1 package com.example.android_data_storage_sdcard; 2 3 import android.test.AndroidTestCase; 4 5 import com.example.android_data_storage_sdcard.file.FileUitls; 6 7 public class MyTest extends AndroidTestCase { 8 9 public void test() {10 FileUitls fileUitls = new FileUitls();11 fileUitls.saveFileToSdcard("keji.txt", "橘子洲頭".getBytes());12 }13 }
android 開發-檔案儲存體之讀寫sdcard