在单个csv文件中,比较两行是否相等

时间:2016-09-17 17:11:09

标签: java file csv

我有一个包含许多行的CSV文件。

1shelf CSV文件示例内容:

#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0005,0,0,,,13
#ManagementNode,BOARD-INFORMATION,NE_ID,RACK_ID,SHELF_ID,SLOT_ID,BOARD_NAME,ACTIVE_MODE,ADMIN_STATE,OPER_STATE,VERSION,SERIAL_NO,MANUFACTURER,MANUFACTURE_DATE
ManagementNode,BOARD-INFORMATION,0005,0,0,6,LEMA0,ACTIVE,UNLOCK,ENABLE,,S61F91571,XYZ,2014-09-03

2shelf CSV文件示例内容:

#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0001,0,0,,,13
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0001,0,1,,,13

请注意,在2shelf文件中,第1行和第3行的标题值相同,第2行第5行值为0,第5行第5行值为1,这意味着它是2shelf文件。 1shelf文件也是如此。

我是Java的新手,能够打印所需的行,但不知道如何实现比较逻辑来找出1shelf或2shelf文件。

BufferedReader in = new BufferedReader (new FileReader("C:\\Files\\1_2_Shelf\\Test.csv"));
        String info = "";
            int startLine = 4;
            int endLine = 7;
            for (int i = 0; i < startLine; i++) { 
                info = in.readLine();
                }
            for (int i = startLine; i < endLine + 1; i++) {
                info = in.readLine();
                System.out.println(info);
            }

            in.close();
        }

1 个答案:

答案 0 :(得分:0)

将下面显示的import添加到您的类文件的顶部。

然后使用info.split(",")将CSV字符串拆分为数组中的字段。

然后你将使用字段index = 4来获取数组的第5个字段(数组元素索引从零开始)。

下面的示例代码,插入到原始代码中:

import java.util.regex.Pattern;    // NEW import to add at top of your file
...

// Some constants for identifying shelves
final int FIELD_SHELF_ID = 4;
final String SHELF1 = "0";
final String SHELF2 = "1";

BufferedReader in = 
    new BufferedReader (new FileReader("C:\\Files\\1_2_Shelf\\Test.csv"));
String info = "";
int startLine = 4;
int endLine = 7;
for (int i = 0; i < startLine; i++) {
    info = in.readLine();
}
for (int i = startLine; i < endLine + 1; i++) {
    info = in.readLine();
    System.out.println(info);

    String infoFields[] = info.split(",");
    System.out.println("infoFields[FIELD_SHELF_ID] = 
        " + infoFields[FIELD_SHELF_ID]);

    switch(infoFields[FIELD_SHELF_ID]) {
        case SHELF1:
            System.out.println("Found 1SHELF row"); break;
        case SHELF2:
            System.out.println("Found 2SHELF row"); break;
        default:
            System.out.println("Unknown shelf-type row"); break;
    }
}

in.close();

如果您使用的是旧版Java,而不是switch语句,则可以使用if/else if/else,如下所示:

if (infoFields[FIELD_SHELF_ID].equals(SHELF1)) {
    System.out.println("Found 1SHELF row");
}
else if (infoFields[FIELD_SHELF_ID].equals(SHELF2)) {
    System.out.println("Found 2SHELF row");
}
else {
    System.out.println("Unknown shelf-type row");
}