gpt4 book ai didi

java - 在 Java 中解析 CSV

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:08 25 4
gpt4 key购买 nike

我有这种奇怪的情况,我必须水平阅读。所以我得到一个 csv 文件,其中包含水平格式的数据。如下所示:

CompanyName,RunDate,10/27/2010,11/12/2010,11/27/2010,12/13/2010,12/27/2010....

RunDate 之后显示的所有日期都是运行日期字段的值,我必须在我的系统中为该公司更新该字段。日期值不是固定的数字,它们可以是单个值到 10 到 n 个数字。所以我需要读取所有这些值并在系统中更新。我正在用 Java 编写这个。

最佳答案

String,split(",") 不太可能起作用。
它会拆分嵌入逗号(“Foo, Inc.”)的字段,即使它们是 CSV 行中的单个字段。

如果公司名称是:
公司, Inc.
或者更糟:
乔的“又好又快又便宜”的食物


根据维基百科: ( http://en.wikipedia.org/wiki/Comma-separated_values )

Fields with embedded commas must be enclosed within double-quote characters.

   1997,Ford,E350,"Super, luxurious truck"

Fields with embedded double-quote characters must be enclosed within double-quote characters, and each of the embedded double-quote characters must be represented by a pair of double-quote characters.

   1997,Ford,E350,"Super ""luxurious"" truck"


更糟糕的是,引用字段可能嵌入了换行符(换行符;“\n”):

Fields with embedded line breaks must be enclosed within double-quote characters.

   1997,Ford,E350,"Go get one now  
they are going fast"



这演示了 String,split(",") 解析逗号的问题:

CSV 行是:

a,b,c,"Company, Inc.", d, e,"Joe's ""Good, Fast, and Cheap"" Food", f, 10/11/2010,1/1/2011, g, h, i


// Test String.split(",") against CSV with
// embedded commas and embedded double-quotes in
// quoted text strings:
//
// Company names are:
// Company, Inc.
// Joe's "Good, Fast, and Cheap" Food
//
// Which should be formatted in a CSV file as:
// "Company, Inc."
// "Joe's ""Good, Fast, and Cheap"" Food"
//
//
public class TestSplit {
public static void TestSplit(String s, String splitchar) {
String[] split_s = s.split(splitchar);

for (String seg : split_s) {
System.out.println(seg);
}
}


public static void main(String[] args) {
String csvLine = "a,b,c,\"Company, Inc.\", d,"
+ " e,\"Joe's \"\"Good, Fast,"
+ " and Cheap\"\" Food\", f,"
+ " 10/11/2010,1/1/2011, h, i";

System.out.println("CSV line is:\n" + csvLine + "\n\n");
TestSplit(csvLine, ",");
}
}


产生以下内容:


D:\projects\TestSplit>javac TestSplit.java

D:\projects\TestSplit>java TestSplit
CSV line is:
a,b,c,"Company, Inc.", d, e,"Joe's ""Good, Fast, and Cheap"" Food", f, 10/11/2010,1/1/2011, g, h, i


a
b
c
"Company
Inc."
d
e
"Joe's ""Good
Fast
and Cheap"" Food"
f
10/11/2010
1/1/2011
g
h
i

D:\projects\TestSplit>



CSV 行应该被解析为:


a
b
c
"Company, Inc."
d
e
"Joe's ""Good, Fast, and Cheap"" Food"
f
10/11/2010
1/1/2011
g
h
i

关于java - 在 Java 中解析 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3908012/

25 4 0
文章推荐: java - Wicket:从浏览器获取 URL
文章推荐: java - 防止 JSPX 创建自闭合标记 (
!=
)
文章推荐: Java2D 图形抗锯齿
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com