Android 내부 저장소에 텍스트 파일 저장/읽기 + 오류 로그 기록 방법


✨ 개요

Android에서는 내부 저장소(Internal Storage)를 사용하여
앱 전용 파일을 안전하게 저장할 수 있습니다.
또한 앱 문제 발생 시, 간단한 로그 파일을 남겨 디버깅이나 분석에 활용할 수도 있습니다.


1. ✅ 앱 내부 저장소란?

2. ✅ 파일 저장: 텍스트 쓰기

val fileName = "text.txt"
val text = "this is text!!"

button.setOnClickListener {
  saveTextToFile(fileName, text)
}

fun Context.saveTextToFile(fileName: String, text: String) {
  openFileOutput(fileName, Context.MODE_PRIVATE).use { outputStream ->
    outputStream.write(text.toByteArray())
  }
}

3. 🔥 파일 읽기: 텍스트 읽어오기

val fileName = "text.txt"

val result = readTextFromFile(fileName)
Log.e(TAG, "result=$result") // this is text!!

fun Context.readTextFromFile(fileName: String): String {
  return try {
    openFileInput(fileName).bufferedReader().use { it.readText() }
  } catch (e: Exception) {
    ""
  }
}

4. 📊 문제 발생 시 오류 로그 저장하기

try {
  val result = 4 / 0
} catch (e: Exception) {
  saveErrorLog(e)
}

fun Context.saveErrorLog(exception: Throwable) {
    val errorLog = "Time: ${System.currentTimeMillis()}\nError: ${exception.stackTraceToString()}\n\n"
    openFileOutput("error_log.txt", Context.MODE_APPEND).use { outputStream ->
        outputStream.write(errorLog.toByteArray())
    }
}

5. 결론



Related Posts