【问题标题】:Comparing 2 columns in 2 csv files in Java在 Java 中比较 2 个 csv 文件中的 2 列
【发布时间】:2012-07-25 16:03:33
【问题描述】:

我有两个带有主键的 csv,我试图将两个键合并,以便我可以将相关的 csv 与正确的键组合成一个,但是现在我只想比较一列中的内容。我的脑子有点空白,我希望通过代码你能弄清楚我前进的方向。我无法让我的数组真正接收字符串。 Java.lang.arrayindexoutofboundsexception

import java.io.; import java.util.;

公共类 UDC { 公共无效搜索(字符串 [][] wat,字符串 [][] ud){

}


public static void main (String [] args) throws IOException
{
    String [] [] cols = {};
    String [] [] cols1={};
    int row =0;
    int row1 =0;
    int j = 0;


/*Scanner s = new Scanner(new File("Watford Update File.csv"));
Scanner c = new Scanner(new File("udc.csv"));
while (s.hasNextLine()){
    String line = s.nextLine();
    cols =line.split(",");
    System.out.println(cols[0]);*/
    Scanner s = new Scanner(new File("file1.csv"));
    Scanner w = new Scanner (new File("file.csv"));
    while (w.hasNextLine())

    {
        String line1 = w.nextLine();    
        System.out.println(cols);
        //cols[row]=line1.split(",");
        row ++;
        if(!w.hasNextLine()){
        while (s.hasNextLine()){
        String line2 = s.nextLine();
         //cols1[row1]=line2.split(",");
        //put while loop in diffrent method but break


            if(cols[j].equals(cols1[row1]))
            {

                j++;
                row1++;
                System.out.print(cols[j]);
                System.out.print(" ");
                System.out.print(cols1[row1]);
                System.out.println();

            }else{
                row1++;

            }

        }


    }
    }

}

}

【问题讨论】:

  • 两列的大小是否相同?如果没有,您可以在 if (cols[j].equals(cols1[row1])) 行获得此异常

标签: java csv compare


【解决方案1】:

您应该使用List<String[]>,而不是为colscols1 使用数组。此外,您的代码非常混乱,因为比较循环与读取循环交织在一起。最好先简单地读入数据,然后进行比较。

public static void main(String [] args)
{
    List<String[]> cols;
    List<String[]> cols1;
    try {
        cols = readFile("udc.csv");
        cols1 = readFile("Watford Update File.csv");
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    // loop through array lists to do your comparisons
    // For example, to compare the first column of rows i and j:
    //    cols.get(i)[0].equals(cols1.get(j)[0])
}

private static List<String[]> readFile(String fileName) throws IOException
{
    List<String[]> values = new ArrayList<String[]>();
    Scanner s = new Scanner(new File("udc.csv"));
    while (s.hasNextLine()) {
        String line = s.nextLine();
        values.add(line.split(","));
    }
    return values;
}

【讨论】:

  • @jbel - 您为colscols1 分配了一个空数组,并且没有任何规定可以使数组增长。 List 自动增长,这就是我推荐它的原因;否则您将不得不为colscols1 实现自己的重新分配例程。
  • 下一步将是实际比较这两个字段并写入第一个 csv 文件,例如,如果我在一个 csv 中有两个列,我计划再添加两个列,并且标题匹配唯一的数字,我一直在研究 supercsv 库,但是根据给我的内容,它看起来不太可能。
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多