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

วิธีอ่านไฟล์ txt จาก External Storage พร้อม Runtime Permission ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีอ่านไฟล์ข้อความ (txt) จาก External Storage พร้อมการขอ Runtime Permission โดยสมมติว่ามีโฟลเดอร์ text และไฟล์ sample.txt อยู่ใน External Storage แล้ว

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

Android Studio → File → New Project → กรอกรายละเอียด

ขั้นตอนที่ 2: ออกแบบ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <Button
        android:id="@+id/read"
        android:text="Read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/output"
        android:layout_width="wrap_content"
        android:textSize="25sp"
        android:layout_height="wrap_content" />
</LinearLayout>

ขั้นตอนที่ 3: เขียน MainActivity.java (แก้ไขให้ถูกต้อง)

package com.example.andy.myapplication;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 100;
    Button read;
    TextView output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        output = findViewById(R.id.output);
        read = findViewById(R.id.read);

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String state = Environment.getExternalStorageState();
                
                if (Environment.MEDIA_MOUNTED.equals(state)) {
                    if (Build.VERSION.SDK_INT >= 23) {
                        if (checkPermission()) {
                            readTextFile();
                        } else {
                            requestPermission();
                        }
                    } else {
                        readTextFile();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "External Storage ไม่พร้อมใช้งาน", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void readTextFile() {
        File sdcard = Environment.getExternalStorageDirectory();
        File dir = new File(sdcard.getAbsolutePath() + "/text/");
        
        if (dir.exists()) {
            File file = new File(dir, "sample.txt");
            StringBuilder text = new StringBuilder();
            
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;
                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                }
                br.close();
                output.setText(text.toString());
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "อ่านไฟล์ล้มเหลว: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "ไม่พบโฟลเดอร์ text ใน External Storage", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Toast.makeText(this, "ต้องการสิทธิ์อ่าน External Storage กรุณาอนุญาตใน Settings", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("value", "Permission Granted");
                readTextFile();
            } else {
                Log.e("value", "Permission Denied");
                Toast.makeText(this, "ไม่ได้รับอนุญาต ไม่สามารถอ่านไฟล์ได้", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
หมายเหตุ: โค้ดต้นฉบับมีโค้ดซ้ำซ้อน (เขียนอ่านไฟล์ 2 ครั้งสำหรับ API < 23 และ >= 23) และข้อผิดพลาดตัวดำเนินการ โค้ดข้างบนได้ปรับปรุงให้สะอาดและถูกต้อง

ขั้นตอนที่ 4: กำหนดสิทธิ์ใน AndroidManifest.xml

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

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

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

การทดสอบและผลลัพธ์

วิธีอ่านไฟล์ txt จาก External Storage พร้อม Runtime Permission ใน Android

วิธีอ่านไฟล์ txt จาก External Storage พร้อม Runtime Permission ใน Android

ข้อมูลเพิ่มเติม

การจัดการ Encoding ภาษาไทย

// ระบุ Encoding เป็น UTF-8 เพื่อรองรับภาษาไทย
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

สำหรับ Android 10+ (Scoped Storage)

แทนที่จะเข้าถึง /storage/emulated/0/text/sample.txt โดยตรง ควรใช้:

  • MediaStore API สำหรับไฟล์สื่อ
  • Storage Access Framework (SAF) ให้ผู้ใช้เลือกไฟล์ด้วยตัวเอง
  • getExternalFilesDir() สำหรับไฟล์ของแอปเอง (ไม่ต้อง Permission)

ตัวอย่างใช้ SAF (แนะนำ)

// เปิด File Picker ให้ผู้ใช้เลือกไฟล์
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
startActivityForResult(intent, READ_REQUEST_CODE);

// ใน onActivityResult
Uri uri = data.getData();
InputStream is = getContentResolver().openInputStream(uri);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

สรุป

การอ่านไฟล์ txt จาก External Storage ต้องขอ READ_EXTERNAL_STORAGE Permission สำหรับ Android 6.0-9.0 สำหรับ Android 10+ ควรใช้ SAF หรือ MediaStore API แทนการเข้าถึงไฟล์โดยตรง