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

Đọc toàn bộ file thành String trong Java (Scanner, NIO)

Đọc file text vào một String duy nhất.

Cách 1: Scanner + StringBuilder (JDK 1.5+)


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

public class FileToStringScanner {
    public static String readFile(String path) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (Scanner sc = new Scanner(new File(path), "UTF-8")) {
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine());
                if (sc.hasNextLine()) sb.append("\n"); // giữ newline
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) throws IOException {
        String content = readFile("E:/test/sample.txt");
        System.out.println(content);
    }
}

Cách 2: Files.readString() – Java 11+ (Ngắn gọn nhất)


import java.nio.file.*;
import java.io.IOException;

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

Cách 3: Files.readAllLines() – Java 7+ (Trả về List<String>)


List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
String content = String.join("\n", lines);

Cách 4: BufferedReader – Tùy chỉnh đọc


try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line).append("\n");
    }
    return sb.toString();
}

So sánh

Phương phápJava versionĐộ phức tạpHiệu năng file lớnEncoding
Scanner1.5+Trung bìnhTrung bìnhTùy chỉnh
Files.readString()11+1 dòngTốt (direct buffer)UTF-8 mặc định
Files.readAllLines()7+2 dòngLoad all RAMTùy chỉnh
BufferedReader1.1+Nhiều dòngTốt (streaming)Tùy chỉnh

⚠️ Cảnh báo file lớn

Đọc toàn bộ file > RAM vào String gây OutOfMemoryError. Với file lớn, hãy xử lý line-by-line (streaming) thay vì load hết.