将CSV值转换为JAVA中的HashMap键值对 [英] Convert CSV values to a HashMap key value pairs in JAVA

查看:286
本文介绍了将CSV值转换为JAVA中的HashMap键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI我有一个名为 test.csv 的csv。我试图逐行读取csv并将值转换为哈希键值对。
下面是代码: -

HI I have a csv called test.csv . I am trying to read the csv line by line and convert the values into a hash key value pairs . Here is the code :-

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文件如下: -

The csv file is as follows :-

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"

运行此代码时会出现以下错误: -

When I run this code I get this error :-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    Example.main(Example.java:33)

任何人都可以帮助我修复代码,并找出我的程序中的错误。

Can anyone please help me to fix the code and find out the error in my program ?

推荐答案

p>在你的字符串中,当你第一次拆分它只包含 arr [0] as 1 c $ c> arr [1] 因此会导致异常

In your String when you split it on first time only contains arr[0] as 1 nothing in arr[1] so it will cause an Exception

如果你不需要1,2等等。可以看下面的代码:

If you does not need the 1,2, etc.. You can look the following code:

        String str[] = line.split(",");
        for(int i=1;i<str.length;i++){
            String arr[] = str[i].split(":");
            map.put(arr[0], arr[1]);
        }

这篇关于将CSV值转换为JAVA中的HashMap键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆