Android File


Android에서 파일을 저장하는 방법은 내부 저장소와 외부 저장소로 나눌 수 있습니다. 각각의 저장소는 특정 목적과 특성을 가지고 있으며, 개발자는 요구 사항에 따라 적절한 저장소를 선택하여 사용합니다. 아래는 내부 저장소와 외부 저장소에 파일을 저장하고 읽고 쓰는 방법에 대한 상세 설명입니다.

내부 저장소

내부 저장소는 앱 전용 저장소로, 앱이 제거되면 해당 저장소의 파일도 함께 제거됩니다. 파일은 앱의 데이터 디렉토리에 저장되며, 다른 앱이 접근할 수 없습니다.

파일 쓰기

String filename = "myfile.txt";
String fileContents = "Hello, World!";
FileOutputStream fos = null;
try {
    fos = openFileOutput(filename, Context.MODE_PRIVATE);
    fos.write(fileContents.getBytes());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

파일 읽기

String filename = "myfile.txt";
FileInputStream fis = null;
try {
    fis = openFileInput(filename);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    String fileContents = sb.toString();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

파일 삭제

String filename = "myfile.txt";
boolean deleted = deleteFile(filename);

외부 저장소

외부 저장소는 SD 카드나 외부 USB 저장소와 같은 사용자가 접근할 수 있는 저장소입니다. 외부 저장소는 퍼블릭 디렉토리와 앱 전용 디렉토리로 나눌 수 있습니다. 퍼블릭 디렉토리는 모든 앱이 접근 가능하지만, 앱 전용 디렉토리는 해당 앱만 접근할 수 있습니다.

퍼미션 설정

외부 저장소를 사용하기 위해서는 매니페스트 파일에 권한을 추가해야 합니다.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

파일 쓰기 (앱 전용 디렉토리)

String filename = "myfile.txt";
String fileContents = "Hello, World!";
File file = new File(getExternalFilesDir(null), filename);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    fos.write(fileContents.getBytes());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

파일 읽기 (앱 전용 디렉토리)

String filename = "myfile.txt";
File file = new File(getExternalFilesDir(null), filename);
FileInputStream fis = null;
try {
    fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    String fileContents = sb.toString();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

파일 삭제 (앱 전용 디렉토리)

String filename = "myfile.txt";
File file = new File(getExternalFilesDir(null), filename);
boolean deleted = file.delete();

퍼블릭 디렉토리 사용

퍼블릭 디렉토리는 모든 앱이 접근할 수 있는 디렉토리입니다. 일반적으로 사진, 동영상, 문서 등과 같은 파일을 저장할 때 사용됩니다.

File publicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
String filename = "myfile.txt";
String fileContents = "Hello, World!";
File file = new File(publicDir, filename);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    fos.write(fileContents.getBytes());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

외부 저장소 접근시 주의 사항

  • 퍼미션: 외부 저장소를 사용하기 위해서는 사용자에게 권한을 요청해야 합니다. Android 6.0 (API 23) 이상에서는 런타임 권한 요청이 필요합니다.
  • 공유 데이터: 퍼블릭 디렉토리에 저장된 데이터는 다른 앱이 접근할 수 있으므로 민감한 데이터를 저장하지 않도록 주의해야 합니다.
  • 사용 가능 여부: 외부 저장소가 항상 사용 가능하지 않을 수 있으므로, 사용 가능 여부를 확인해야 합니다.
boolean isExternalStorageWritable() {
    return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}

boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}

종합

Android의 내부 저장소와 외부 저장소를 사용하면 애플리케이션 내에서 다양한 파일을 관리할 수 있습니다. 내부 저장소는 보안이 필요한 데이터를 저장하는 데 적합하며, 외부 저장소는 사용자와 공유되는 데이터를 저장하는 데 유용합니다. 적절한 저장소를 선택하여 데이터의 안전성과 접근성을 고려하는 것이 중요합니다.


Leave a Reply

Your email address will not be published. Required fields are marked *