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

วิธีอ่านไฟล์ข้อความธรรมดาในแอป Android ด้วย Kotlin

อ่านไฟล์ข้อความจากโฟลเดอร์ raw

ตัวอย่างนี้แสดงวิธีอ่านไฟล์ข้อความ (.txt) ที่จัดเก็บในโฟลเดอร์ res/raw ของแอป Android โดยใช้ Kotlin

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

สร้างโปรเจกต์ Android ใหม่ใน Android Studio ตามปกติ

ขั้นตอนที่ 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"
    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: สร้างไฟล์ข้อความใน res/raw

คลิกขวาที่โฟลเดอร์ res > New > Android Resource Directory เลือก Resource type: raw แล้วสร้างไฟล์ sample.txt วางข้อความทดสอบไว้ภายใน

ขั้นตอนที่ 4: เขียนโค้ดอ่านไฟล์ (src/MainActivity.kt)

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

    fun readTextFile(view: View) {
        val stringBuilder = StringBuilder()
        val inputStream: InputStream = resources.openRawResource(R.raw.sample)
        val reader = BufferedReader(InputStreamReader(inputStream))

        try {
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                stringBuilder.append(line).append("\n")
            }
            textView.text = stringBuilder.toString()
            Toast.makeText(baseContext, stringBuilder.toString(), Toast.LENGTH_LONG).show()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            inputStream.close()
        }
    }
}

ขั้นตอนที่ 5: กำหนดค่า Manifest

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

ผลลัพธ์

กดปุ่ม "Read Text File" จะอ่านเนื้อหาจากไฟล์ sample.txt ใน raw resources แล้วแสดงใน TextView และ Toast