Ghi tệp CSV có định dạng
Sau khi làm sạch dữ liệu, bạn cần xuất dữ liệu cho nhiều đối tượng khác nhau. Nhóm phân tích muốn CSV chuẩn, các hệ thống châu Âu mong đợi dấu chấm phẩy làm bộ phân tách, còn một hệ thống mainframe cũ yêu cầu tệp không có tiêu đề. Tùy chọn xuất linh hoạt giúp dữ liệu của bạn tích hợp trơn tru trên nhiều môi trường kỹ thuật khác nhau.
Các lớp Table và CsvWriteOptions đã được nhập sẵn cho bạn.
Bài tập này là một phần của khóa học
Nhập dữ liệu trong Java
Hướng dẫn bài tập
- Ghi bảng dưới dạng CSV chuẩn.
- Ghi với bộ phân tách là dấu chấm phẩy.
- Ghi không có tiêu đề để dùng cho hệ thống cũ.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
public class WriteCSVFiles {
public static void main(String[] args) {
try {
Table employeePerformance = Table.read().csv("employee_performance.csv");
System.out.println("Original data structure:");
System.out.println(employeePerformance.structure());
System.out.println("First 3 rows:");
System.out.println(employeePerformance.first(3));
// Write the table as a standard CSV
employeePerformance.____.csv("employee_performance_standard.csv");
// Write with a semicolon separator
employeePerformance.write().csv(CsvWriteOptions
.____("employee_performance_semicolon.csv")
.____(';')
.build());
// Write without headers for a legacy system
employeePerformance.write().csv(CsvWriteOptions
.builder("employee_performance_noheader.csv")
.____(____)
.build());
System.out.println("\nFiles successfully written to output directory.");
Table readBack = Table.read().csv("employee_performance_standard.csv");
System.out.println("\nVerification - Reading back semicolon-separated file:");
System.out.println(readBack.first(3));
} catch (Exception e) {
System.err.println("Error processing CSV files: " + e.getMessage());
}
}
}