在java中解析分割的csv文件

在java中解析分割的csv文件,java,csv,Java,Csv,我有一个带有注释的csv文件,其值需要在两个ArrayList之间拆分。例如: % the values below here should go % into ArrayList<Integer> list1 3,4,5,2,2,3 5,6,3,2,4,5 3,2,3,4,5,6 2,3,4,5,1,3 % the values below here should go % into ArrayList<Integer> list2 4,6,3,4,5,3 3,4,5,

我有一个带有注释的csv文件,其值需要在两个ArrayList之间拆分。例如:

% the values below here should go
% into ArrayList<Integer> list1
3,4,5,2,2,3
5,6,3,2,4,5
3,2,3,4,5,6
2,3,4,5,1,3
% the values below here should go
% into ArrayList<Integer> list2
4,6,3,4,5,3
3,4,5,6,3,2
4,5,6,4,3,2
%下面的值应该是
%进入ArrayList列表1
3,4,5,2,2,3
5,6,3,2,4,5
3,2,3,4,5,6
2,3,4,5,1,3
%下面的值应该是
%进入ArrayList列表2
4,6,3,4,5,3
3,4,5,6,3,2
4,5,6,4,3,2
实现这一目标的最佳方式是什么?我应该使用一个计数器,每次状态从%变为某个值时递增,或者反之亦然,然后如果计数器%2=0,则添加一个新的ArrayList并开始写入它吗?这是我能想到的唯一方法,但它似乎有点笨拙,还有谁有更好的主意吗


编辑:我已经编写了实际解析csv值的代码,我不需要帮助,只是想知道如何将值拆分为两个列表。

你的建议听起来不错。如果文件格式真的如此可预测,那么在我看来,任何更复杂的方法都可能是矫枉过正

但是如果你想看到一种不同的方法,这就是我的想法:每一行不是以
%
开头的,都是我们想要解析为
数组列表的东西。因此,每当您遇到一行不是注释的行时,就开始将以下行解析为
ArrayList
,直到找到另一条注释或文件的结尾。这两个选项都标记要存储在单个
ArrayList
中的零件的末尾。比如说:

ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currentArray;
while(inputStream.hasNextLine()) {
    String line = inputStream.getLine();
    if(!lineIsComment(line)) {
        // This means that we are in a number block. We store the numbers
        // either in an existing list or create a new one if necessary
        if(currentArray == null) {
            currentArray = new ArrayList<Integer>();
        }
        addToList(line, currentArray);
    } else if(currentArray != null) {
        // In this case a comment block starts and currentArray contains
        // the numbers of the last number block.
        arrays.add(currentArray);
        currentArray = null;
    }
}
if(currentArray != null) arrays.add(currentArray);
ArrayList数组=新的ArrayList();
ArrayList当前数组;
while(inputStream.hasNextLine()){
String line=inputStream.getLine();
如果(!lineIsComment(line)){
//这意味着我们在一个数字块中。我们存储数字
//在现有列表中,或根据需要创建新列表
如果(currentArray==null){
currentArray=新的ArrayList();
}
addToList(行、当前数组);
}else if(currentArray!=null){
//在这种情况下,注释块启动,currentArray包含
//最后一个数字块的数字。
add(currentArray);
currentArray=null;
}
}
if(currentArray!=null)数组。添加(currentArray);

其中,
lineIsComment(String-line)
返回一个布尔值,指示给定的行是否为注释,
addToList(String-line,ArrayList-list)
使用您的方法解析一行数字并将其存储在提供的列表中。

它们有多种方式,但我认为除了你上面提到的以外,没有更好的/最佳的方法。