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

วิธีอ่านไฟล์ .txt ด้วย RandomAccessFile ใน Java

java.io.RandomAccessFile อ่าน/เขียนไฟล์แบบ Random Access (Jump ไปมาที่ไหนก็ได้) ใช้ File Pointer ควบคุมตำแหน่ง

คุณสมบัติหลัก

  • Mode: "r" (Read), "rw" (Read/Write), "rws", "rwd"
  • getFilePointer() - ตำแหน่งปัจจุบัน (long)
  • seek(long pos) - กระโดดไปตำแหน่ง
  • readLine() - อ่านบรรทัด (คืน String, null ถ้า EOF)
  • length() - ขนาดไฟล์ (bytes)

ตัวอย่าง: อ่านไฟล์ทั้งหมดบรรทัดต่อบรรทัด

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRead {
    public static void main(String[] args) throws IOException {
        String filePath = "D:/input.txt";
        
        // 1. File Object
        File file = new File(filePath);
        
        // 2. RandomAccessFile (Mode "r" = Read Only)
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            StringBuilder content = new StringBuilder();
            String line;
            
            // 3. อ่านจนกว่า Pointer จะถึง End of File
            while (raf.getFilePointer() < raf.length()) {
                line = raf.readLine();
                if (line != null) {
                    content.append(line).append(System.lineSeparator());
                }
            }
            
            System.out.println("File Contents:\n" + content.toString());
        }
    }
}

ตัวอย่าง: Random Access (อ่านเฉพาะส่วน)

try (RandomAccessFile raf = new RandomAccessFile("data.txt", "r")) {
    // ข้ามไปที่ Byte ที่ 100
    raf.seek(100);
    
    // อ่าน 50 Bytes
    byte[] buffer = new byte[50];
    int read = raf.read(buffer);
    System.out.println(new String(buffer, 0, read));
    
    // กลับไปต้นไฟล์
    raf.seek(0);
    System.out.println("First line: " + raf.readLine());
}

RandomAccessFile vs BufferedReader

Feature RandomAccessFile BufferedReader
Access Pattern Random (Seek) Sequential Only
Read/Write ทั้งคู่ (rw) Read Only
Performance (Sequential) ช้ากว่า (No Buffer) เร็ว (Buffered)
Encoding Support Manual (Bytes -> String) Built-in (Charset)

ข้อควรระวัง

  • readLine() ใช้ Platform Default Encoding อาจมีปัญหา Thai/Unicode -> ควรอ่าน Bytes แล้ว Decode เอง
  • ไม่มี Buffer เอง สำหรับ Sequential Read ใหญ่ๆ ควรใช้ BufferedReader แทน
  • Thread-Safe สำหรับ Single Instance

สรุป

ใช้ RandomAccessFile เมื่อต้องการ Random Access (Seek, Skip, Partial Read/Write) สำหรับอ่านไฟล์ปกติ Sequential ใช้ BufferedReader หรือ Scanner จะเร็วและง่ายกว่า