開始使用免費開始

讀取 CSV 檔案

你剛加入 DataCorp 擔任初級資料分析師。你的第一個專案要整併員工資料庫,但資料來自多個系統,而且使用不同的 CSV 格式——有的是逗號分隔,有的是 tab 分隔。能處理不同的檔案格式非常關鍵,因為真實世界的資料很少只有一種標準格式。

TableCsvReadOptions,以及相關的 Tablesaw 類別都已為你匯入。

本練習屬於課程

Java 中的資料匯入

檢視課程

練習說明

  • 使用預設選項讀取 "employees.csv"
  • 使用 tab 分隔符讀取 "employees_tab.csv"
  • 列印兩個資料表的結構。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class ReadCSVFiles {
    public static void main(String[] args) {
        try {
            // Read file using default options
            Table standardCsv = Table.____().____("employees.csv");
            
            // Read file using a tab delimiter
            Table tabDelimited = Table.read().csv(CsvReadOptions
                .____("employees_tab.csv")
                .____('\t')
                .build());
            
            // Print the structure of both tables
            System.out.println(____.____());
            System.out.println(____.____());
            
        } catch (Exception e) {
            System.err.println("Error reading CSV files: " + e.getMessage());
        }
    }
}
編輯並執行程式碼