開始使用免費開始

建立基本的檔案讀取器

你在一家追蹤產業趨勢的新創擔任資料分析師。你的團隊每天都會收到含有市場資料的 CSV 檔案,需要加以處理。作為建立資料管線的第一步,你需要一個可靠的方法來讀取這些檔案,並在處理前先確認它們是否存在。

FilePathPathsFiles 類別已為你匯入。

本練習屬於課程

Java 中的資料匯入

檢視課程

練習說明

  • 使用檔案路徑建立一個 File 物件。
  • 檢查檔案是否存在。
  • 取得檔案大小(位元組)。
  • 由檔案路徑建立一個 Path 物件。

動手互動練習

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

public class BasicFileReaders {
    public static void main(String[] args) {
        String filePath = "sample_market_data.csv";
        
        // Create a File object
        File file = new File(____);
        
        // Check if the file exists
        System.out.println("File exists: " + ____.____());
        
        // Get the file size in bytes
        System.out.println("Size: " + ____.____() + " bytes");
        
        try {
            // Create a Path object from the file path
            Path path = Paths.____(filePath);            
            List lines = Files.readAllLines(path);           
            System.out.println("Total lines: " + lines.size());
            System.out.println("Header: " + lines.get(0));
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
編輯並執行程式碼