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

วิธีสร้าง String จากเนื้อหาไฟล์ใน Java

อ่านไฟล์ทั้งหมดเข้า String ใน Java มีหลายวิธี วิธีคลาสสิกคือใช้ Scanner

วิธีที่ 1: ใช้ Scanner (Classic)


import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FileToStringScanner {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(new File("E:\\test\\sample.txt"));
        StringBuilder sb = new StringBuilder();
        
        while (sc.hasNextLine()) {
            sb.append(sc.nextLine()).append("\n");
        }
        
        System.out.println("File content:\n" + sb.toString());
    }
}

วิธีที่ 2: ใช้ Files.readString() (Java 11+) - แนะนำมากที่สุด


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileToStringModern {
    public static void main(String[] args) throws IOException {
        String content = Files.readString(Paths.get("E:\\test\\sample.txt"));
        System.out.println("File content:\n" + content);
    }
}

วิธีที่ 3: ใช้ Files.readAllBytes() (Java 7+)


String content = new String(Files.readAllBytes(Paths.get("file.txt")), StandardCharsets.UTF_8);

วิธีที่ 4: ใช้ BufferedReader (Manual Control)


try (BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"), StandardCharsets.UTF_8)) {
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    String content = sb.toString();
}

ตัวอย่างไฟล์ทดสอบ (sample.txt)


Tutorials Point is an E-learning company that set out on its journey to provide knowledge 
to that class of readers that responds better to online content. With Tutorials Point, 
you can learn at your own pace, in your own space. After a successful journey of providing 
the best learning content at tutorialspoint.com, we created our subscription based premium 
product called Tutorix to provide Simply Easy Learning in the best personalized way for 
K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.

การเปรียบเทียบ

วิธีJava VersionEncodingMemoryคะแนน
Scanner1.5Default platformLoad ทั้งไฟล์⭐⭐
Files.readString()11UTF-8 (default)Load ทั้งไฟล์⭐⭐⭐⭐⭐
Files.readAllBytes()7ManualLoad ทั้งไฟล์⭐⭐⭐⭐
BufferedReader1.1ManualStreaming ได้⭐⭐⭐
Files.lines() Stream8UTF-8Lazy stream⭐⭐⭐⭐

สำหรับไฟล์ใหญ่ (Large Files) - ใช้ Streaming


// Process line by line without loading all into memory
Files.lines(Paths.get("large-file.txt"), StandardCharsets.UTF_8)
     .filter(line -> line.contains("ERROR"))
     .forEach(System.out::println);

ข้อควรระวัง

  • ระบุ Charset (UTF-8) เสมอ เพื่อความเข้ากันได้ข้าม platform
  • Scanner ใช้ default charset ของ platform (อาจแตกต่างใน Windows vs Linux)
  • Files.readString() โหลดทั้งไฟล์เข้า RAM - ไม่เหมาะกับไฟล์ > 100MB
  • ปิด resource ให้หมด (try-with-resources)