Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách đọc file text từ thư mục raw trong Android

Giới thiệu

Bài viết này hướng dẫn cách đọc file text đơn giản đặt trong thư mục res/raw/ của dự án Android. Thư mục raw dùng để lưu trữ file nguyên bản (raw resources) như text, json, csv, mp3...

Các bước thực hiện

Bước 1: Tạo dự án và thêm file text

  1. Tạo project Android Studio mới
  2. Chuột phải vào res → New → Android Resource Directory
  3. Directory name: raw, Resource type: raw
  4. Copy file text (ví dụ: sample.txt) vào thư mục res/raw/

Bước 2: Layout (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">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Đọc file text trong Android"
        android:textAlignment="center"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btnReadFile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:onClick="readTextFile"
        android:text="Đọc File Text" />

    <TextView
        android:id="@+id/tvContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnReadFile"
        android:layout_marginTop="10dp"
        android:textSize="16sp" />

</RelativeLayout>

Bước 3: Code Java đọc file (src/MainActivity.java)

package app.com.sample;

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;

public class MainActivity extends AppCompatActivity {

    TextView tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvContent = findViewById(R.id.tvContent);
    }

    public void readTextFile(View view) {
        StringBuilder stringBuilder = new StringBuilder();

        try {
            // Mở file từ res/raw/sample.txt
            // R.raw.sample được tự động generate, KHÔNG cần extension .txt
            InputStream inputStream = getResources().openRawResource(R.raw.sample);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }

            reader.close();
            inputStream.close();

            // Hiển thị lên TextView
            tvContent.setText(stringBuilder.toString());

            // Hiển thị Toast (tùy chọn)
            Toast.makeText(this, "Đọc file thành công!", Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            e.printStackTrace();
            tvContent.setText("Lỗi đọc file: " + e.getMessage());
            Toast.makeText(this, "Lỗi: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

Lưu ý quan trọng:

  • Truy cập file qua R.raw.tên_file (không có phần mở rộng)
  • File trong res/raw/ không được nén, giữ nguyên định dạng
  • Dùng BufferedReader để đọc hiệu quả dòng per dòng
  • Luôn đóng stream trong block finally hoặc try-with-resources (Java 7+)

Bước 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

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

Chạy ứng dụng

Chạy app, nhấn nút "Đọc File Text", nội dung file sample.txt sẽ hiển thị trong TextView.

Cách đọc file text từ thư mục raw trong Android

Cách đọc file từ Assets (thay thế)

Nếu file lớn hoặc cần truy cập theo đường dẫn, dùng thư mục assets/:

InputStream is = getAssets().open("filename.txt");

Kotlin Version (Coroutine + use)

lifecycleScope.launch(Dispatchers.IO) {
    val content = resources.openRawResource(R.raw.sample).bufferedReader().use { it.readText() }
    withContext(Dispatchers.Main) {
        tvContent.text = content
    }
}