【发布时间】:2018-04-06 06:48:31
【问题描述】:
这似乎是一个很容易解决的问题,但我一直坚持下去。任何人都可以帮助我并解释我在哪里做错了吗? 我读了一个 csv 文件:
Time,Activ,Switch,A,B,C,D,E
5:58,on,,,,,,
6:00,on 123,,,ab cd,,,
6:02,on - off,1->2,6,ab cd,1,,
6:04,on,,,cd ab,1,,
6:06,off,,,,,,
7:22,on / off,,,,,,
7:30,on / of,3->4,15,,,,
7:34,home on,,,ab cd,,,
我想只用逗号分隔一行中的数据并保存到看起来像的数组中(第一行省略):
1---> ["5:58","on", "", "", "", "", "", ""]
2---> ["6:00", "on 123", "", "", "ab cd", "", "", ""]
3---> ["6:02", "on - off", "1->2", "6", "ab cd", "1", "", ""]
6---> ["7:22", "on / off", "3->4", "15", "", "", "", ""]
等等......但我收到的数组也被空格和其他字符分割字符串
1---> ["5:58","on", "", "", "", "", "", ""]
2---> ["6:00", "on", "123", "", "", "ab", "cd", "", "", ""]
3---> ["6:02", "on", "-", "off", "1->2", "6", "ab", "cd", "1", "", ""]
6---> ["7:22", "on", "/", "off", "3->4", "15", "", "", "", ""]
这是我的代码:
public class Test {
public static void main(String []args) {
String fileName = "TestData.csv";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
String firstLine = inputStream.next();
while(inputStream.hasNext()){
String dataRow = inputStream.next();
String[] valuesInDataRow = dataRow.split(",",-1);
for(int i=0;i<valuesInDataRow.length;i++){
System.out.println("---> " + valuesInDataRow[i]);
}
}
inputStream.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
我会非常感谢任何解释:)
【问题讨论】: