API IO trong Java
Java cung cấp một bộ API mạnh mẽ cho việc đọc và ghi dữ liệu (Input/Output). API này bao gồm các lớp để làm việc với file, stream, và các nguồn dữ liệu khác nhau.
1. Đọc và Ghi File
FileInputStream và FileOutputStream
// Ghi file
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String content = "Hello World";
fos.write(content.getBytes());
}
// Đọc file
try (FileInputStream fis = new FileInputStream("input.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// Xử lý dữ liệu đọc được
System.out.write(buffer, 0, bytesRead);
}
}
FileReader và FileWriter
// Ghi file text
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Hello World");
}
// Đọc file text
try (FileReader reader = new FileReader("input.txt")) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
// Xử lý dữ liệu đọc được
System.out.write(buffer, 0, charsRead);
}
}
2. Buffered IO
BufferedReader và BufferedWriter
// Ghi file với buffer
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Line 1");
writer.newLine();
writer.write("Line 2");
}
// Đọc file với buffer
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
BufferedInputStream và BufferedOutputStream
// Ghi file với buffer
try (BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("output.txt"))) {
String content = "Hello World";
bos.write(content.getBytes());
bos.flush();
}
// Đọc file với buffer
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("input.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
// Xử lý dữ liệu đọc được
System.out.write(buffer, 0, bytesRead);
}
}
3. Character Streams
InputStreamReader và OutputStreamWriter
// Chuyển đổi từ byte stream sang character stream
try (InputStreamReader reader = new InputStreamReader(
new FileInputStream("input.txt"), "UTF-8")) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
// Xử lý dữ liệu đọc được
System.out.write(buffer, 0, charsRead);
}
}
// Chuyển đổi từ character stream sang byte stream
try (OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("output.txt"), "UTF-8")) {
writer.write("Hello World");
}
4. NIO (New IO)
Path và Files
// Tạo và xóa file
Path path = Paths.get("test.txt");
Files.createFile(path);
Files.delete(path);
// Đọc file
List<String> lines = Files.readAllLines(path);
// Ghi file
Files.write(path, "Hello World".getBytes());
// Sao chép file
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
DirectoryStream
// Liệt kê các file trong thư mục
try (DirectoryStream<Path> stream = Files.newDirectoryStream(
Paths.get("."), "*.txt")) {
for (Path path : stream) {
System.out.println(path);
}
}
5. Ví Dụ Thực Tế
Xử Lý File Log
public class LogManager {
private final Path logFile;
public LogManager(String logFilePath) {
this.logFile = Paths.get(logFilePath);
}
public void writeLog(String message) {
try {
String logEntry = LocalDateTime.now() + " - " + message + "\n";
Files.write(logFile, logEntry.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
public List<String> readLogs() {
try {
return Files.readAllLines(logFile);
} catch (IOException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
}
Xử Lý File Cấu Hình
public class ConfigManager {
private final Path configFile;
private Properties properties;
public ConfigManager(String configPath) {
this.configFile = Paths.get(configPath);
this.properties = new Properties();
loadConfig();
}
private void loadConfig() {
try (InputStream input = Files.newInputStream(configFile)) {
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveConfig() {
try (OutputStream output = Files.newOutputStream(configFile)) {
properties.store(output, "Configuration");
} catch (IOException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return properties.getProperty(key);
}
public void setProperty(String key, String value) {
properties.setProperty(key, value);
saveConfig();
}
}
6. Best Practices
-
Sử Dụng Try-With-Resources
// Không nên
FileReader reader = new FileReader("file.txt");
try {
// Xử lý file
} finally {
reader.close();
}
// Nên
try (FileReader reader = new FileReader("file.txt")) {
// Xử lý file
} -
Xử Lý Ngoại Lệ Đúng Cách
// Không nên
try {
Files.readAllLines(path);
} catch (Exception e) {
e.printStackTrace();
}
// Nên
try {
Files.readAllLines(path);
} catch (IOException e) {
logger.error("Lỗi đọc file: " + e.getMessage());
} -
Sử Dụng Buffer Khi Cần
// Không nên
FileReader reader = new FileReader("large.txt");
// Nên
BufferedReader reader = new BufferedReader(new FileReader("large.txt"));
7. Lỗi Thường Gặp
-
Quên Đóng Stream
// Lỗi
FileReader reader = new FileReader("file.txt");
// Quên đóng stream
// Đúng
try (FileReader reader = new FileReader("file.txt")) {
// Xử lý file
} -
Xử Lý File Không Tồn Tại
// Lỗi
Files.readAllLines(Paths.get("nonexistent.txt"));
// Đúng
Path path = Paths.get("nonexistent.txt");
if (Files.exists(path)) {
Files.readAllLines(path);
} -
Quên Xử Lý Encoding
// Lỗi
new FileReader("file.txt"); // Sử dụng encoding mặc định
// Đúng
new InputStreamReader(
new FileInputStream("file.txt"),
StandardCharsets.UTF_8
);