在CSV文件中提取带有搜索值的所有行

时间:2018-12-03 01:30:11

标签: java csv

我对此感到无所适从。我正在尝试打印具有特定值的CVS文件中的所有行。因此,代码逐行搜索并打印具有特定搜索值的所有行值。这就是我目前所拥有的

import java.io.File;
import java.util.Scanner;

public class Test {
    public static void main(String args[]) {
        String filename = "bos-2016-reg-csv-tables.csv";
        String searchValue = "LC0601_01";

        File file = new File(filename);
        try{
            Scanner inputStream = new Scanner(file);
            inputStream.nextLine();      // ignore the first line

            while(inputStream.hasNextLine()) {
                String data = inputStream.nextLine();
            String[] value = data.split(",");
            if(searchValue.equals(value)){
               // TODO
            }

        }

    } catch (Exception e) {
        System.out.println(e);
    }
}
}

2 个答案:

答案 0 :(得分:1)

好吧,dataTableComboBox_DropDownClosedif(searchValue.equals(value))String)与searchValueString[])进行比较,因此始终为假。

此外,最好将数组拆分为列表后再利用其value方法:

contains

答案 1 :(得分:0)

我能够弄清楚。

public class Test {

public static List<String[]> readData() throws IOException {
    String searchTerm = "LC1506";
    int count = 0;
    String file = "bos-2016-reg-csv-tables.csv";
    List<String[]> content = new ArrayList<>();
    try(BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line = "";
        while ((line = br.readLine()) != null) {
            content.add(line.split(","));
        }

        for (String[] aContent : content) {
            for (String value : aContent) {
                if(value.equals(searchTerm)) {
                    System.out.println(Arrays.toString(aContent));
                }
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println(e);
    }
    return content;
}

public static void main(String args[]) {

    try {
        readData();
    } catch (IOException e) {
        System.out.println(e);
    }
}}