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

Java中拆分带双引号逗号分隔的CSV内容问题求助

Hey there! Let's work through your CSV processing problem step by step. It looks like you're trying to read CSV lines, extract specific fields, and format output in a custom way—let's get this sorted.

First, let's address a common pitfall with your current approach: using split(",") can break if your CSV has fields with commas inside quotes (even if your current data doesn't, it's a good habit to avoid this). Instead, let's use methods that respect CSV's quoted structure.

Option 1: Quick Fix for Simple CSV (No Quoted Commas)

If your CSV doesn't have commas inside quoted fields, we can use a regex to extract each quoted field properly. Here's how to adjust your code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CsvHandler {
    public static void main(String[] args) {
        String csvPath = "your_file.csv";
        // Regex to capture text inside quotes: "([^"]*)"
        Pattern fieldMatcher = Pattern.compile("\"([^\"]*)\"");

        try (BufferedReader reader = new BufferedReader(new FileReader(csvPath))) {
            String line;
            // Uncomment below if you need to skip the header line
            // reader.readLine();
            
            while ((line = reader.readLine()) != null) {
                Matcher matcher = fieldMatcher.matcher(line);
                String[] fields = new String[6]; // Match your 6-field structure
                int fieldIndex = 0;

                // Extract each quoted field
                while (matcher.find() && fieldIndex < fields.length) {
                    fields[fieldIndex++] = matcher.group(1);
                }

                // Make sure we have all required fields before formatting
                if (fieldIndex == 6) {
                    String firstName = fields[2]; // 3rd field (0-indexed)
                    String lastName = fields[4];  // 5th field
                    String output = String.format("%s_%s : %s", firstName, lastName, line);
                    System.out.println(output);
                } else {
                    System.err.println("Skipping invalid line: " + line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

For production code, using a dedicated CSV parser is way better—it handles edge cases like escaped quotes, commas inside fields, and varying line formats automatically. OpenCSV is a great choice here.

Step 1: Add OpenCSV Dependency

If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.6</version>
</dependency>

Step 2: Code with OpenCSV

import com.opencsv.CSVReader;
import java.io.FileReader;

public class RobustCsvHandler {
    public static void main(String[] args) {
        String csvPath = "your_file.csv";

        try (CSVReader reader = new CSVReader(new FileReader(csvPath))) {
            String[] lineFields;
            // Skip header if needed
            // reader.readNext();

            while ((lineFields = reader.readNext()) != null) {
                // Check if we have all 6 fields
                if (lineFields.length >= 6) {
                    String firstName = lineFields[2];
                    String lastName = lineFields[4];
                    
                    // Reconstruct the original quoted line (or just use the raw line if you keep track of it)
                    StringBuilder originalLine = new StringBuilder();
                    for (String field : lineFields) {
                        if (originalLine.length() > 0) originalLine.append(",");
                        originalLine.append("\"").append(field).append("\"");
                    }

                    String output = String.format("%s_%s : %s", firstName, lastName, originalLine.toString());
                    System.out.println(output);
                } else {
                    System.err.println("Invalid line: " + String.join(",", lineFields));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key Notes

  • Field Indices: In your example, the order is EmpID(0), User ID(1), First Name(2), Location(3), Last Name(4), JobCode(5)—so adjust these indices if your actual CSV has a different order.
  • Header Handling: If your CSV starts with a header line, uncomment the reader.readLine() or reader.readNext() line to skip it before processing data lines.
  • Robustness: The OpenCSV approach is preferred because it handles all CSV nuances you might encounter later, like fields with commas or escaped quotes (e.g., "Doe, John" or "O\"Neil").

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:41:50