Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีอ่านไฟล์จาก Assets ใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตการอ่านไฟล์ข้อความ (Text File) จากโฟลเดอร์ Assets ใน Android โดยใช้ AssetManager และ InputStream

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project

ขั้นตอนที่ 2: 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"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        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="16dp"
        android:textAlignment="center"
        android:textColor="@android:color/holo_purple"
        android:textStyle="bold"
        android:text="Tap button to read file" />

    <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>

ขั้นตอนที่ 3: สร้างไฟล์ใน Assets

  1. คลิกขวาที่โฟลเดอร์ app → New → Folder → Assets Folder → Finish
  2. คลิกขวาที่ assets → New → File → ตั้งชื่อ myText.txt
  3. ใส่เนื้อหาตัวอย่าง:
    Hello from Assets folder!
    This is a sample text file.
    Read using Kotlin in Android.
    Support Thai: สวัสดีครับ

ขั้นตอนที่ 4: MainActivity.kt

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.BufferedReader
import java.io.InputStreamReader

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 {
            readFromAssets()
        }
    }

    private fun readFromAssets() {
        try {
            // วิธีที่ 1: ใช้ BufferedReader (แนะนำสำหรับไฟล์ขนาดใหญ่)
            assets.open("myText.txt").use { inputStream ->
                BufferedReader(InputStreamReader(inputStream)).use { reader ->
                    val content = reader.readText()
                    runOnUiThread { textView.text = content }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread { 
                textView.text = "Error reading file: ${e.message}" 
            }
        }
    }
}

วิธีอ่านไฟล์ Assets แบบต่างๆ

วิธีโค้ดเหมาะสำหรับ
InputStream + BufferedReaderassets.open("file.txt").bufferedReader().readText()Text file ขนาดใหญ่ อ่านทีละบรรทัดได้
InputStream.readBytes()assets.open("file.txt").readBytes().toString(Charsets.UTF_8)ไฟล์เล็ก อ่านครั้งเดียว
ScannerScanner(assets.open("file.txt")).use { it.next() }Parse ข้อมูลแบบมีรูปแบบ
Kotlin Extensionassets.open("file.txt").readText() (ต้อง import kotlin.io.path.readText)สั้นที่สุด

อ่านไฟล์ JSON จาก Assets

import org.json.JSONObject

private fun loadJsonFromAssets(filename: String): JSONObject? {
    return try {
        val jsonString = assets.open(filename).bufferedReader().readText()
        JSONObject(jsonString)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

แสดงรายการไฟล์ใน Assets

val files = assets.list("") // root assets folder
files?.forEach { fileName ->
    Log.d("Assets", "File: $fileName")
}

// หรือใน Subfolder
val subFiles = assets.list("subfolder")

ขั้นตอนที่ 5: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.readassets">
    <application ... >
        <activity android:name=".MainActivity"> ... </activity>
    </application>
</manifest>

หมายเหตุสำคัญ

  • Assets เป็น Read-only ไม่สามารถเขียน/แก้ไขไฟล์ได้ใน Runtime
  • ไฟล์ใน Assets จะถูกบีบอัด (Compress) อัตโนมัติ ยกเว้น副檔名ที่กำหนดใน aaptOptions { noCompress "txt", "json", "mp3" }
  • ขนาดไฟล์ Assets เดียวต้อง < 1MB (บางรุ่น) ควรแยกไฟล์ใหญ่
  • ใช้ use { } (Extension Function) เพื่อปิด Stream อัตโนมัติ ป้องกัน Leak
  • รองรับ Subfolder: assets.open("folder/file.txt")

การทดสอบ

รันแอป กดปุ่ม "Read Text from Assets" ข้อความจาก myText.txt จะแสดงใน TextView