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

如何在Java中加载含多空格的CSV文件并完整打印内容

解决Java中加载带空格的CSV并完整打印表格的问题

嘿,我来帮你搞定这个CSV加载和打印的问题!从你描述的情况来看,问题出在CSV的字段包含空格(比如Date列的May 18)、字段前后有冗余空格,以及Codes列包含多个空格分隔的值——普通的字符串分割方式很容易把这些空格误判成分隔符或者保留冗余空格,导致表格打印混乱或者字段解析不完整。

下面给你两种可行的解决方案:


方案一:手动解析适合理解原理

因为你的CSV结构是固定的(5列,前4列是单值可能带空格,最后一列Codes是多值),可以通过定位逗号位置来精准分割字段,同时去除冗余空格:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ManualCSVReader {
    public static void main(String[] args) {
        String filePath = "your-csv-file.csv"; // 替换成你的CSV路径

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 读取并打印表头
            if ((line = br.readLine()) != null) {
                line = line.trim();
                int[] commaIndices = findCommaPositions(line);
                String salesNumHeader = line.substring(0, commaIndices[0]).trim();
                String accountNumHeader = line.substring(commaIndices[0]+1, commaIndices[1]).trim();
                String dateHeader = line.substring(commaIndices[1]+1, commaIndices[2]).trim();
                String deliveryHeader = line.substring(commaIndices[2]+1, commaIndices[3]).trim();
                String codesHeader = line.substring(commaIndices[3]+1).trim();
                
                // 格式化打印表头,让列对齐
                System.out.printf("%-12s %-12s %-10s %-10s %-20s%n", 
                    salesNumHeader, accountNumHeader, dateHeader, deliveryHeader, codesHeader);
            }

            // 读取每行数据并解析
            while ((line = br.readLine()) != null) {
                line = line.trim();
                int[] commaIndices = findCommaPositions(line);
                
                String salesNum = line.substring(0, commaIndices[0]).trim();
                String accountNum = line.substring(commaIndices[0]+1, commaIndices[1]).trim();
                String date = line.substring(commaIndices[1]+1, commaIndices[2]).trim();
                String delivery = line.substring(commaIndices[2]+1, commaIndices[3]).trim();
                String codes = line.substring(commaIndices[3]+1).trim();

                // 格式化打印每行数据,保持列对齐
                System.out.printf("%-12s %-12s %-10s %-10s %-20s%n", 
                    salesNum, accountNum, date, delivery, codes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 辅助方法:找到一行中前4个逗号的位置
    private static int[] findCommaPositions(String line) {
        int[] indices = new int[4];
        int currentIndex = -1;
        for (int i = 0; i < 4; i++) {
            currentIndex = line.indexOf(',', currentIndex + 1);
            indices[i] = currentIndex;
        }
        return indices;
    }
}

方案二:用OpenCSV库更稳定推荐

手动解析只适合结构固定的简单CSV,如果你以后遇到更复杂的情况比如字段包含逗号,手动处理会很麻烦。用OpenCSV这类成熟的库可以轻松处理带空格、冗余空格的CSV:

1. 先添加依赖Maven项目

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.6</version> <!-- 可以用最新稳定版 -->
</dependency>

2. 代码实现

import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;

import java.io.FileReader;
import java.io.IOException;

public class OpenCSVReader {
    public static void main(String[] args) {
        String filePath = "your-csv-file.csv";

        // 配置解析器:忽略字段前后的空格,用逗号作为分隔符
        CSVParser parser = new CSVParserBuilder()
                .withSeparator(',')
                .withIgnoreLeadingWhiteSpace(true)
                .build();

        try (CSVReader reader = new CSVReaderBuilder(new FileReader(filePath))
                .withCSVParser(parser)
                .build()) {

            String[] header = reader.readNext();
            if (header != null) {
                // 格式化打印表头
                System.out.printf("%-12s %-12s %-10s %-10s %-20s%n", 
                    header[0], header[1], header[2], header[3], header[4]);
            }

            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                // nextLine已经是处理好的字段数组,直接格式化打印
                System.out.printf("%-12s %-12s %-10s %-10s %-20s%n", 
                    nextLine[0], nextLine[1], nextLine[2], nextLine[3], nextLine[4]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

为什么你之前无法完整打印?

大概率是用了String.split(",")这类简单分割方式:

  • 它会保留字段前后的冗余空格,导致打印时排版混乱
  • 如果字段本身包含空格比如May 18,虽然split不会拆分这个字段,但冗余空格会让列对齐失效
  • 若Codes列的内容被错误处理,也会导致表格不完整

用上面的两种方法,不管是手动精准分割还是用库解析,都能正确识别每个字段,再配合格式化打印printf,就能完整输出整齐的CSV表格了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:01:35