이 튜토리얼에서는 Kotlin을 사용하여 안드로이드 앱에서 간단한 텍스트 파일을 읽어 화면에 출력하는 방법을 단계별로 알아봅니다. 프로젝트 생성부터 레이아웃 구성, 리소스 파일 준비, 그리고 실제 파일을 읽어오는 코드 작성까지 전체 과정을 예제와 함께 살펴보겠습니다.
1단계: 새 프로젝트 만들기
Android Studio를 실행한 후 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 빈 액티비티(Empty Activity) 템플릿을 선택하고 프로젝트 이름, 패키지명 등 필수 항목을 모두 입력한 뒤 프로젝트를 만들어 주세요.
2단계: 레이아웃 XML 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 버튼 하나와 텍스트를 표시할 TextView 두 개로 구성된 간단한 레이아웃입니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:onClick="readTextFile"
android:text="Read Text File" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Read text File in Android"
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>3단계: raw 리소스 폴더에 텍스트 파일 추가
읽어올 텍스트 파일이 필요합니다. res 폴더를 마우스 오른쪽 버튼으로 클릭한 뒤 New → Android Resource Directory를 선택하고 리소스 타입을 raw로 지정하여 새 디렉터리를 생성합니다. 그다음 해당 폴더 안에 sample.txt 같은 텍스트 파일을 추가하면 됩니다. 이 파일의 내용이 앱에서 읽어지게 됩니다.
4단계: MainActivity.kt 코드 작성
src/MainActivity.kt 파일에 아래 코드를 추가합니다. 버튼을 클릭하면 readTextFile() 메서드가 호출되어 raw 폴더의 텍스트 파일을 한 줄씩 읽어 StringBuilder에 담고, 그 결과를 TextView와 Toast로 표시합니다.
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
fun readTextFile(view: View) {
var string: String? = ""
val stringBuilder = StringBuilder()
val `is`: InputStream = this.resources.openRawResource(R.raw.sample)
val reader = BufferedReader(InputStreamReader(`is`))
while (true) {
try {
if (reader.readLine().also { string = it } == null) break
} catch (e: IOException) {
e.printStackTrace()
}
stringBuilder.append(string).append("\n")
textView.text = stringBuilder
}
`is`.close()
Toast.makeText(baseContext, stringBuilder.toString(),
Toast.LENGTH_LONG).show()
}
}코드 핵심 포인트
resources.openRawResource(R.raw.sample): res/raw 폴더의 sample 파일을 InputStream으로 엽니다.BufferedReader.readLine(): 파일을 한 줄씩 읽으며, null이 반환되면 파일의 끝에 도달한 것입니다.StringBuilder: 읽어 들인 문자열을 누적하여 최종적으로 TextView에 출력합니다.IOException처리: 파일 입출력 중 발생할 수 있는 예외를 try-catch로 안전하게 처리합니다.
5단계: AndroidManifest.xml 확인
androidManifest.xml 파일이 아래와 같이 되어 있는지 확인합니다. 별도의 권한 없이 내부 리소스를 읽는 예제이므로 특별한 추가 설정은 필요하지 않습니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 연결된 모바일 기기를 선택하면, 잠시 후 기본 화면이 표시됩니다.

버튼을 누르면 raw 폴더에 저장된 텍스트 파일의 내용이 화면의 TextView에 출력되고, 동시에 Toast 메시지로도 확인할 수 있습니다. 이처럼 Kotlin과 안드로이드의 리소스 시스템을 활용하면 몇 줄의 코드만으로도 텍스트 파일을 손쉽게 읽어올 수 있습니다.