Đọ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áp | Java version | Độ phức tạp | Hiệu năng file lớn | Encoding |
|---|---|---|---|---|
| Scanner | 1.5+ | Trung bình | Trung bình | Tùy chỉnh |
| Files.readString() | 11+ | 1 dòng | Tốt (direct buffer) | UTF-8 mặc định |
| Files.readAllLines() | 7+ | 2 dòng | Load all RAM | Tùy chỉnh |
| BufferedReader | 1.1+ | Nhiều dòng | Tố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.