将 CSV 值转换为 JAVA 中的 HashMap 键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20068383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert CSV values to a HashMap key value pairs in JAVA
提问by Newbie
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 :-
嗨,我有一个名为 .csv 的 csv test.csv
。我正在尝试逐行读取 csv 并将值转换为哈希键值对。这是代码:-
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);
}
}
The csv file is as follows :-
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"
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 ?
任何人都可以帮我修复代码并找出我程序中的错误吗?
采纳答案by Rakesh KR
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
在字符串中,当你把它分解的第一次只包含arr[0]
如1
没有在arr[1]
这样就会导致异常
If you does not need the 1,2, etc.. You can look the following code:
如果不需要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]);
}
回答by Hussain Akhtar Wahid 'Ghouri'
using openCSV would be one way to do it
使用 openCSV 将是一种方法
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
the jar is available here
罐子在这里可用
回答by Alexis C.
The problem is that when you split
your str
, the first element in each line is alone (i.e 1 and 2). So arr
only contains ["1"]
, and hence arr[1]
doesn't exists.
问题是,当你split
你str
,在每行的第一个元素是单独(即1和2)。所以arr
只包含["1"]
,因此arr[1]
不存在。
I.e for the example input :
即对于示例输入:
1,"testCaseName":"ACLTest"
split by ,
=> str
contains {1, testCaseName:ACLTest}
split by :
at the first iteration => arr contains {1}
split by ,
=>在第一次迭代时str
包含{1, testCaseName:ACLTest}
split by :
=> arr 包含{1}
Example :
例子 :
String s = "1,testCaseName:ACLTest";
String str[] = s.split(",");
System.out.println(Arrays.toString(str));
for(String p : str){
String arr[] = p.split(":");
System.out.println(Arrays.toString(arr));
}
Output :
输出 :
[1, testCaseName:ACLTest]
[1] //<- here arr[1] doesn't exists, you only have arr[0] and hence the ArrayIndexOutOfBoundsException when trying to access arr[1]
[testCaseName, ACLTest]
要修复您的代码(如果您不想使用 CSV 解析器),请让您的循环从 1 开始:
for(int i=1;i<str.length;i++){
String arr[] = str[i].split(":");
map.put(arr[0], arr[1]);
}
另一个问题是
HashMap
HashMap
使用hashCode
hashCode
键来存储(键,值)对。So when insering "testCaseName":"ACLTest"
and "testCaseName":"DCLAddTest"
, the first value will be erased and replace by the second one :
因此,在插入"testCaseName":"ACLTest"
and 时"testCaseName":"DCLAddTest"
,第一个值将被擦除并替换为第二个值:
Map<String, String> map = new HashMap<>();
map.put("testCaseName","ACLTest");
map.put("testCaseName","DCLAddTest");
System.out.println(map);
Output :
输出 :
{testCaseName=DCLAddTest}
So you have to fix that too.
所以你也必须解决这个问题。
回答by Marek Puchalski
Look at the output of the call
String arr[] = str[i].split(":");
arr[1] does not exists for the first element in your CSV file which happens to be 1, 2... You can start the loop with int i=0 to fix this issue.
查看调用String arr[] = str[i].split(":");
arr[1]的输出
对于 CSV 文件中的第一个元素不存在,该元素恰好为 1, 2 ... 您可以使用 int i=0 启动循环以解决此问题。
回答by tom
String.split is rubbish for parsing CSV. Either use the Guava Splitter or a proper CSV parser. You can parse CSV into beans using the Hymanson CSV mapper like this:
String.split 是解析 CSV 的垃圾。使用 Guava Splitter 或适当的 CSV 解析器。您可以使用 Hymanson CSV 映射器将 CSV 解析为 bean,如下所示:
public class CSVPerson{
public String firstname;
public String lastname;
//etc
}
CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader().withColumnSeparator(delimiter);
MappingIterator<CSVPerson> it = = mapper.reader(CSVPerson).with(schema).readValues(input);
while (it.hasNext()){
CSVPerson row = it.next();
}
more info at http://demeranville.com/how-not-to-parse-csv-using-java/
更多信息请访问http://demeranville.com/how-not-to-parse-csv-using-java/
回答by cri_sys
Beside the problem you have with the first number which its not a pair and its causing the Exception, you will not want to use Hashmap, since hashmap use a unique key, so line 2 will replace values from line 1.
除了第一个数字不是一对并且导致异常的问题之外,您将不想使用 Hashmap,因为 hashmap 使用唯一键,因此第 2 行将替换第 1 行中的值。
You should use a MultiMap, or a List of pairs in this case.
在这种情况下,您应该使用 MultiMap 或对列表。
回答by Kechit Goyal
Using FasterXML's CSV package: https://github.com/FasterXML/Hymanson-dataformats-text/tree/master/csv
使用 FasterXML 的 CSV 包:https: //github.com/FasterXML/Hymanson-dataformats-text/tree/master/csv
public static List<Map<String, String>> read(File file) throws JsonProcessingException, IOException {
List<Map<String, String>> response = new LinkedList<Map<String, String>>();
CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Map<String, String>> iterator = mapper.reader(Map.class)
.with(schema)
.readValues(file);
while (iterator.hasNext()) {
response.add(iterator.next());
}
return response;
}
回答by dimuthu93
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Example {
public static void main(String[] args) {
String csvFile = "test.csv";
String line = "";
String cvsSplitBy = ",";
HashMap<String, String> list = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
//System.out.println(country[0] +" " + country[1]);
list.put(country[0], country[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(list);
}
// enter code here
}