理解数据导入基础

Java 中的数据导入

Anthony Markham

VP Quant Developer

认识您的讲师!

 

$$

Anthony Markham

  • 副总裁,量化开发/分析负责人
  • 投资银行领域的 C++/Java/Python 开发者
  • 具备高校教学经验

 

Anthony Markham

Java 中的数据导入

数据导入基础

  • 对 Java 应用处理外部信息至关重要

  • 常见格式:CSV(逗号分隔值)、JSON、Excel

导入流程的五个步骤流程图

  • Java 在 java.iojava.nio 中提供了强大的工具
Java 中的数据导入

文件处理基础

  • File 类表示文件或目录
  • 通过 exists(), length(), isDirectory() 等方法验证文件
import java.io.File;
File dataFile = new File("data.csv");
boolean exists = dataFile.exists();
long size = dataFile.length();
boolean isDirectory = dataFile.isDirectory();
Java 中的数据导入

Path 接口与 Files 类

  • Path 接口与 Files 类提供现代文件操作(java.nio
  • 优点:更灵活、更好的异常处理与性能
  • 简单操作用 java.io;高性能 I/O 用 java.nio
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
Path dataPath = Paths.get("data.csv");

boolean exists = Files.exists(dataPath); long size = Files.size(dataPath);
Java 中的数据导入

读取文本文件

  • Files.readAllLines(): 将整个文件读入 List<String>(每行一个元素)
  • Files.readString(): 将整个文件读入单个字符串
Path file = Paths.get("data.csv");

// 一次性读取所有行 List<String> lines = Files.readAllLines(file); // 将整个文件读取为字符串 String content = Files.readString(file);

$$

$$

  • 整个文件会加载到内存中 🛑
Java 中的数据导入

数据验证

  • 在处理前确保数据质量
  • 检查数据质量与结构
  • 执行常见校验
  • 处理任意 Exception

数据验证检查

Java 中的数据导入

数据验证

  • 常见检查:文件非空、表头含必需列
  • 用 try-catch 块处理 Exception
try {
  Path file = Paths.get("data.csv");
  List<String> lines = Files.readAllLines(file);
  if (lines.isEmpty()) { // 验证文件有内容
      System.out.println("Warning: File is empty");}
  String header = lines.get(0);
  if (!header.contains("id") || !header.contains("name")) {    // 检查表头
      System.out.println("Error: File missing required columns");
} catch (Exception e) {
    System.out.println("Error reading file: " + e.getMessage());}
Java 中的数据导入

小结

类/接口 方法 说明
File new File() 创建文件路径的抽象表示
File exists() 检查文件是否存在
File length() 获取文件大小(字节)
Paths get() 由字符串创建 Path 对象
Files exists() 检查文件是否存在(现代 API)
Files size() 获取文件大小(字节,现代 API)
Files readAllLines() 将整个文件读入 List<String>
Files readString() 将整个文件读入单个 String
1 https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html
Java 中的数据导入

Passons à la pratique !

Java 中的数据导入

Preparing Video For Download...