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

วิธีสร้างไฟล์ข้อความและเขียนข้อมูลใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการสร้างไฟล์ข้อความ (Text File) และเขียนข้อมูลลงไปใน Internal Storage ของ Android

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

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 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:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#008080"
        android:padding="5dp"
        android:text="Android เขียนข้อความลงไฟล์"
        android:textColor="#fff" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:layout_margin="5dp">
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:text="เขียนข้อความลงไฟล์"
        android:onClick="WriteBtn"
        android:layout_margin="5dp" />

</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)

package com.example.sample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText textmsg;
    static final int READ_BLOCK_SIZE = 100;

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

    // เขียนข้อความลงไฟล์
    public void WriteBtn(View v) {
        try {
            // โหมด MODE_PRIVATE = เฉพาะแอปนี้เข้าถึงได้
            FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
            outputWriter.write(textmsg.getText().toString());
            outputWriter.close();

            // แสดงข้อความสำเร็จ
            Toast.makeText(getBaseContext(), "บันทึกไฟล์สำเร็จ!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ขั้นตอนที่ 4: กำหนดค่า AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.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>

โหมดการเปิดไฟล์ (File Output Modes)

โหมด คำอธิบาย
MODE_PRIVATE ค่าเริ่มต้น เฉพาะแอปของคุณเข้าถึงได้ (ทับไฟล์เดิม)
MODE_APPEND ต่อข้อมูลท้ายไฟล์ (ไม่ทับไฟล์เดิม)
MODE_WORLD_READABLE Deprecated (API 17+) - อื่นๆ อ่านได้
MODE_WORLD_WRITABLE Deprecated (API 17+) - อื่นๆ เขียนได้

การทดสอบ

รันแอปบนอุปกรณ์จริง พิมพ์ข้อความใน EditText กดปุ่ม "เขียนข้อความลงไฟล์\" จะแสดง Toast ยืนยัน

วิธีสร้างไฟล์ข้อความและเขียนข้อมูลใน Android

หมายเหตุ: ไฟล์จะถูกเก็บที่ /data/data/<package_name>/files/ และจะถูกลบเมื่อ Uninstall แอป