开始使用免费开始使用

创建基础文件读取器

您在一家跟踪行业趋势的初创公司担任数据分析师。团队每天都会收到包含市场数据的 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());
        }
    }
}
编辑并运行代码