嗨,我有一个
这是代码:-public class Example {
public static void main(String[] args) throws ParseException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new FileReader("test.csv"));
String line = null;
HashMap<String,String> map = new HashMap<String, String>();
while((line=br.readLine())!=null){
String str[] = line.split(",");
for(int i=0;i<str.length;i++){
String arr[] = str[i].split(":");
map.put(arr[0], arr[1]);
}
}
System.out.println(map);
}
}
csv文件如下:-1,"testCaseName":"ACLTest","group":"All_Int","projectType":"GEN","vtName":"NEW_VT","status":"ACTIVE","canOrder":"Yes","expectedResult":"duplicateacltrue"
2,"testCaseName":"DCLAddTest","group":"India_Int","projectType":"GEN_NEW","vtName":"OLD_VT","status":"ACTIVE","canOrder":"Yes","expectedResult":"invalidfeaturesacltrue"
当我运行此代码时,我得到此错误:-Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
Example.main(Example.java:33)
谁能帮我修复代码并找出程序中的错误?
最佳答案
第一次拆分时,在您的字符串中仅包含arr[0]
,因为1
在arr[1]
中没有任何内容,因此将导致异常
如果不需要1,2等。您可以查看以下代码:
String str[] = line.split(",");
for(int i=1;i<str.length;i++){
String arr[] = str[i].split(":");
map.put(arr[0], arr[1]);
}
关于java - 在JAVA中将CSV值转换为HashMap键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620834/