本文介绍了Java-根据列将CSV解析为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想寻求有关此任务的帮助:我有这样的CSV例如:
column1$column2$column3
123$xyz$321
456$zyx$654
我想通过Java将其解析为列/标题的Arrays/Array列表->例如
ArrayList column1 = [123,456]
ArrayList column2 = [xyz,zyx]
ArrayList column3 = [321,654]
谢谢大家.
解决方案
这就是我要这样做的方式...,请注意要将列放在另一个List中的方法,以减少代码并提高动态性.
>
public static void main(String[] args) {
ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("testing.cvs"));
while ((sCurrentLine = br.readLine()) != null) {
String[] fields = sCurrentLine.split("\\$");
for (int i = 0; i < fields.length; i++) {
if (columns.size()<=i){
columns.add(new ArrayList<String>());
}
columns.get(i).add(fields[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I would like to ask for help with this task:I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by Java to Arrays / Array lists by columns / headers -> for example
ArrayList column1 = [123,456]
ArrayList column2 = [xyz,zyx]
ArrayList column3 = [321,654]
Thanks everyone.
解决方案
This is how I would have done this..., note the metod to put the columns in another List for less code and to be more dynamic.
public static void main(String[] args) {
ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("testing.cvs"));
while ((sCurrentLine = br.readLine()) != null) {
String[] fields = sCurrentLine.split("\\$");
for (int i = 0; i < fields.length; i++) {
if (columns.size()<=i){
columns.add(new ArrayList<String>());
}
columns.get(i).add(fields[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
这篇关于Java-根据列将CSV解析为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!