我有这种 CSV 文件,我必须用 Java 解析。
2012-11-01 00, 1106, 2194.1971066908
2012-11-01 01, 760, 1271.8460526316
.
.
.
2012-11-30 21, 1353, 1464.0014781966
2012-11-30 22, 1810, 1338.8331491713
2012-11-30 23, 1537, 1222.7826935589
720 rows selected.
Elapsed: 00:37:00.23
这是我创建的 Java 代码,用于分隔每一列并将其存储在列表中。
public void extractFile(String fileName){
try{
BufferedReader bf = new BufferedReader(new FileReader(fileName));
try {
String readBuff = bf.readLine();
while (readBuff!=null){
Pattern checkData = Pattern.compile("[a-zA-Z]");
Matcher match = checkData.matcher(readBuff);
if (match.find()){
readBuff = null;
}
else if (!match.find()){
String[] splitReadBuffByComma = new String[3];
splitReadBuffByComma = readBuff.split(",");
for (int x=0; x<splitReadBuffByComma.length; x++){
if (x==0){
dHourList.add(splitReadBuffByComma[x]);
}
else if (x==1){
throughputList.add(splitReadBuffByComma[x]);
}
else if (x==2){
avgRespTimeList.add(splitReadBuffByComma[x]);
}
}
}
readBuff = bf.readLine();
}
}
finally{
bf.close();
}
}
catch(FileNotFoundException e){
System.out.println("File not found dude: "+ e);
}
catch(IOException e){
System.out.println("Error Exception dude: "+e);
}
}
问题是我创建的正则表达式有点错误,因为它仍然包含文本“选择了 720 行”并将它们存储在 dHourList 中。
dHourList 应该只存储像这样表示的日期列 "2012-11-01 00...etc"
throughputList = "1106, 760 ...etc"
avgResponseTime = "2194.192, 1271.846...etc"
正确的 reg 表达式应该是什么?
更新
2012-11-30 21 2012-11-30 22 2012-11-30 23
选择了 720 行。
经过:00:37:00.23
日期小时大小:724 吞吐量大小:720 平均响应时间大小:720
我在 checkData 正则表达式中使用了这个,因为如果我使用一个斜杠 \d 编译会说无效的转义序列
Pattern checkData = Pattern.compile("^(19|20)\\d\\d([-/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])\b.+$");
但它仍然显示选择了 720 行和另一行不应该在那里。
更新 2
工作代码:
while (readBuff!=null){
Pattern checkData = Pattern.compile("^(19|20)\\d\\d([-/.])(0[1-9]|1[012])\\2(0[1-9]|[12][0-9]|3[01])\\b.+$");
Matcher match = checkData.matcher(readBuff);
if (!match.find()){
readBuff = null;
}
else{
String[] splitReadBuffByComma = new String[3];
splitReadBuffByComma = readBuff.split(",");
for (int x=0; x<splitReadBuffByComma.length; x++){
if (x==0){
dHourList.add(splitReadBuffByComma[x]);
}
else if (x==1){
throughputList.add(splitReadBuffByComma[x]);
}
else if (x==2){
avgRespTimeList.add(splitReadBuffByComma[x]);
}
}
}
readBuff = bf.readLine();
}
我删除了 else if 条件并将其更改为 else 并使用 Cylian 建议的正则表达式现在我有输出
2012-11-30 21
2012-11-30 22
2012-11-30 23
Size of date-hour: 720 size of throughput: 720 size of avg resp time: 720
非常感谢!