You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不读取整个大CSV文件将其截断至指定行数?Java有相关API吗?

Java提取大型CSV文件前100行的实现方案

Java完全可以处理这种场景,不需要额外依赖,用标准库就能实现,核心思路是逐行读取文件,避免一次性加载整个大文件到内存。下面提供两种实用的实现方式:

方式一:使用BufferedReader逐行读写

这是最传统且内存效率极高的方式,不管文件多大,每次只在内存中保留一行数据:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class CsvTruncator {
    public static void main(String[] args) {
        String inputCsv = "path/to/your/large.csv";
        String outputCsv = "path/to/truncated.csv";
        int targetLines = 100;

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(inputCsv), StandardCharsets.UTF_8));
             BufferedWriter writer = new BufferedWriter(
                     new OutputStreamWriter(new FileOutputStream(outputCsv), StandardCharsets.UTF_8))) {

            String line;
            int lineCount = 0;
            while ((line = reader.readLine()) != null && lineCount < targetLines) {
                writer.write(line);
                writer.newLine();
                lineCount++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 优点:内存占用极低,仅需存储当前读取的一行数据,适合任何大小的文件
  • 注意:代码中指定了UTF-8编码,可根据你的CSV文件实际编码调整

方式二:使用Java 8+ Stream API简化实现

利用Files.lines生成流式数据,结合limit操作直接截取前N行,代码更简洁:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public class CsvTruncatorStream {
    public static void main(String[] args) {
        String inputCsv = "path/to/your/large.csv";
        String outputCsv = "path/to/truncated.csv";
        int targetLines = 100;

        try {
            String truncatedContent = Files.lines(Paths.get(inputCsv), StandardCharsets.UTF_8)
                    .limit(targetLines)
                    .collect(Collectors.joining(System.lineSeparator()));

            Files.write(Paths.get(outputCsv), truncatedContent.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 优点:代码简洁,利用Stream API的声明式风格,可读性强
  • 注意:如果前100行的总内容极大(比如每行几MB),truncatedContent会占用较多内存,但CSV文件通常每行数据不会这么夸张,大部分场景下完全适用

额外提示

  • 如果你的CSV文件包含表头,上述代码会自动保留表头(第一行),因为读取是从文件开头开始的
  • 若需要跳过表头再取100行数据,只需在循环或Stream中先调用一次readLine()或skip(1)即可

内容的提问来源于stack exchange,提问作者hololensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:45:14