始める無料で始める

基本的なファイルリーダーの作成

業界トレンドを追跡するスタートアップでデータアナリストとして働いているとします。チームには毎日、市場データを含む 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());
        }
    }
}
コードを編集して実行