Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 애셋(Assets) 폴더의 파일 읽는 방법

Kotlin으로 Android 애셋(Assets) 폴더의 파일 읽기

이 예제에서는 Kotlin을 사용하여 Android 앱의 assets 폴더에 저장된 텍스트 파일을 읽어 화면에 출력하는 방법을 단계별로 살펴봅니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File > New Project로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계 — 레이아웃 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?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"
    tools:context=".MainActivity">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:layout_centerHorizontal="true"
    android:text="Tutorials Point"
    android:textAlignment="center"
    android:textColor="@android:color/holo_green_dark"
    android:textSize="32sp"
    android:textStyle="bold" />
<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:padding="24sp"
    android:textAlignment="center"
    android:textColor="@android:color/holo_purple"
    android:textStyle="bold" />
<Button
    android:id="@+id/btnReadText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:layout_marginBottom="30dp"
    android:text="Read text from assets"
    android:textStyle="bold" />
</RelativeLayout>

레이아웃은 상단에 타이틀 텍스트, 중앙에 파일 내용을 표시할 TextView, 하단에 파일을 읽어오는 Button으로 구성되어 있습니다.

3단계 — assets 폴더 및 텍스트 파일 생성

프로젝트 창에서 app 폴더를 마우스 오른쪽 버튼으로 클릭한 후 New > Folder > Assets Folder를 선택하여 assets 폴더를 생성합니다. 이어서 assets 폴더를 마우스 오른쪽 버튼으로 클릭하고 New > File을 선택한 뒤 myText.txt라는 이름의 파일을 만들고, 원하는 텍스트 내용을 입력합니다.

4단계 — MainActivity.kt 구현

src/MainActivity.kt 파일에 다음 코드를 추가합니다.

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.IOException
import java.io.InputStream

class MainActivity : AppCompatActivity() {
    private lateinit var button: Button
    private lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        textView = findViewById(R.id.textView)
        button = findViewById(R.id.btnReadText)

        button.setOnClickListener {
            var string: String? = ""
            try {
                val inputStream: InputStream = assets.open("myText.txt")
                val size: Int = inputStream.available()
                val buffer = ByteArray(size)
                inputStream.read(buffer)
                string = String(buffer)
            } catch (e: IOException) {
                e.printStackTrace()
            }
            textView.text = string
        }
    }
}

핵심 동작 방식은 다음과 같습니다. 버튼이 클릭되면 assets.open() 메서드로 myText.txt 파일의 입력 스트림을 열고, available()로 파일 크기를 확인한 만큼 바이트 배열을 생성한 후 데이터를 읽어들입니다. 그다음 바이트 배열을 문자열로 변환하여 TextView에 표시하며, 파일 입출력 과정에서 발생할 수 있는 IOException은 try-catch 블록으로 처리합니다.

5단계 — 매니페스트 설정

AndroidManifest.xml이 아래와 같이 설정되어 있는지 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘Kotlin으로 안드로이드 애셋(Assets) 폴더의 파일 읽는 방법을 클릭합니다. 목록에서 자신의 모바일 기기를 선택하면 해당 기기에 앱이 실행되어 기본 화면이 표시됩니다.

앱이 실행되면 하단의 'Read text from assets' 버튼을 눌러 보세요. assets 폴더에 저장된 텍스트 파일의 내용이 화면 중앙의 TextView에 그대로 출력되는 것을 확인할 수 있습니다.

Kotlin으로 안드로이드 애셋(Assets) 폴더의 파일 읽는 방법