'외장메모리'에 해당되는 글 1건

  1. 2010.06.17 안드로이드 ROM/SD 파일 쓰기
Mobile Dev/Android2010. 6. 17. 17:06
안드로이드 프로그래밍을 하다보면 파일 핸들링을 해야 하는 경우가 있다.
안드로이드에서 파일을 핸들링 할 수 있는 곳은 기본 내장되어 있는 롬(ROM)과 외장메모리(SD 메모리 카드) 이렇게 두 곳을 사용할 수 있다.
그러나 외장메모리는 항상 마운트되어 있다고 보장을 할 수 없으며, 그렇다고 용량이 한정되어 있는 내장 롬을 무조건 사용한다는 것도 좋은 방밥은 아니다.
그래서 외장메모리의 마운트 여부를 확인하여 기본적으로 외장메모리를 사용하게하며, 외장 메모리가 마운트 되어 있지 않다면 내장롬을 사용하게 하는 것이 좋은 방법일 듯 싶다.

아래는 외장메모리의 마운트 여부를 확인하고, 그에 따라 파일을 원하는 위치에 쓰는 샘플이다.

// 외장메모리를 체크하여 최상위 패스를 설정한다.
String saveFilePath = null;
String ext = Environment.getExternalStorageState();
if (ext.equals(Environment.MEDIA_MOUNTED)) {
   
// 외장메모리가 마운트 되어 있을 때
    saveFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
   
// 외장메모리가 마운트 되어 있지 않을 때
    saveFilePath = Environment.getDataDirectory().getAbsolutePath();
}

File saveFile = null;
FileOutputStream fos = null;
try {
   
// 파일 저장 디렉토리 설정 (없으면 생성)
    File fold = new File(saveFilePath + File.separator + dir);
    if (!fold.exists()) {
        fold.mkdir();
    }
   
// 파일 저장
    saveFile = new File(saveFilePath + File.separator + dir + File.separator + fileName);
    fos = new FileOutputStream(saveFile);
   
byte[] buf = new byte[2048];
    int readLength = 0;
    while ((readLength = resIn.read(buf)) != -1) {
        fos.write(buf, 0, readLength);
    }
} finally {
    if (resIn != null)  resIn.close();
    if (fos != null) fos.close();
}

외장메모리 쓰기 권한을 주는 것을 잊지 말자!!!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Posted by as.wind.914