如何根据 JAVA 中的用户输入从 CSV 中筛选记录并将新记录添加到 CSV 文件

How to filter records from CSV and add new records to CSV file based on User input in JAVA

我正在学习 JAVA 并编写一个基本程序,并试图找出一种方法来从我的 CSV 中过滤现有记录并根据用户输入将新记录添加到我的 CSV 文件中。当用户输入所需的输入时,我正在检查用户输入是否与 CSV 文件中的记录匹配。我想显示相关输入的所有匹配记录。我有不同的方法来完成这项工作。我还创建了一个单独的方法,应该将输入的任何新记录添加到 CSV 文件中。为此,我在下面做 -

import java.util.Scanner;

public class FilterAndAddEmployeeData {

   ArrayList<Employee>employeeList; // Employeee class is a POJO here

       Scanner userInput = new Scanner(System.in);
       File file = new File("data.csv");
       Employee emp = new Employee(); // This will expect parameters similar to POJO I believe

   public void findByName(String fName, String lName) {
         
          File file = new File(data.csv);
          Scanner x = null;
          System.out.println("Enter first name:")
          String fName = x.next();
          System.out.println("Enter last name:")
          String lName = x.next();
          while(x.hasNextLine()) {
            String fileData = x.next();
            String inputStream = fileData.split(',');
            for(String i: inputStream){
             System.out.println(i); // This will print all 5 rows of my CSV
            }
           }
         }


    public void findById(String id) {
     // TO - DO
    }
    
    public void addEmployee(Employee emp){
     employeeList.add(emp); // To add employee details inputted by user in the employee object
    }
}

在这里,我的员工 class 是一个单独的 class,它只有 getter 和 setter 以及成员数据。我在 main() 中调用了这三个独立的方法。 我可以打印不带逗号的 CSV 文件。问题是我无法根据用户输入从 CSV 中过滤记录。例如,如果我输入名字和姓氏,控制台应该从我的 CSV 中打印相应的记录,否则 return null。有人可以帮我理解这个吗?我的 CSV 文件有 5 行,包含 First Name、Last Name、Age、Employee ID 字段。

编辑(按照以下建议):

public void findByName(String fName, String lName) {
Scanner userInput = new Scanner(System.in);
File file = new File("data.csv");


try {
    fileScanner = new Scanner(file);
    fileData = userInput.nextLine();
    System.out.print("Enter first name: --> ");
    String fName = userInput.nextLine().trim();
    System.out.print("Enter last name: --> ");
    String lName = userInput.nextLine().trim();
  //  List<String> foundRecords = new ArrayList<>();
    boolean found = false;
    while (fileScanner.hasNextLine()) {
        fileData = userInput.nextLine().trim();
        // Skip blank lines (if any).
        if (fileData.isEmpty()) {
            continue;
        }

/* The 'Regular Expression' (regex) to use in the String#split() method.
   This will handle any spacing around the comma delimiter when splitting.
   This eliminate the need to carry out array element trimming of leading
   or trailing whitespaces.                                            */
        String regex = "\s*,\s*";
        String[] lineParts = fileData.split(regex);
/* Based on the header line information we know that First Name
   data is going to be in column index 0 and the Last Name data
   is going to be in column index 1.                  */
        found = (fName.isEmpty() && lName.isEmpty()) ||
                (lineParts[0].equalsIgnoreCase(fName) && lName.isEmpty()) ||
                (fName.isEmpty() && lineParts[1].equalsIgnoreCase(lName)) ||
                (lineParts[0].equalsIgnoreCase(fName) && lineParts[1].equalsIgnoreCase(lName));
Employee emp = new Employee(lineParts[0],lineParts[1], lineParts[2])
        if (found) {
            employeeList.add(emp);
            found = false;
        }
    }

    // Display found records (if any)
    System.out.println();
    System.out.println("Found Records:");
    System.out.println("====================================");
    if (employeeList.isEmpty()) {
        System.out.println("         No Records Found!");
    }
    else {
        for (Employee str : employeeList) {
            System.out.println(str);
        }
    }
    System.out.println("====================================");

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

}

split 有这个签名 public String[] split(String regex)。所以你可以像 String name = inputStream[3] 这样索引到 String[] 来检索一些值。然后你可以应用条件逻辑,如:

if ( name.equals(firstName)) {
    System.out.println("output");
}

当心错误的输入,例如列值中嵌入的逗号。

这是完成此类事情的一种方式的示例(请阅读代码中的注释)。确实没有那么多代码,只是其中有很多可以删除的注释。这只是一个简单的演示:

Scanner userInput = new Scanner(System.in);
File file = new File("data.csv");
String fileData = "";
try (Scanner reader = new Scanner(file)) {
    // Read the header line so we don't deal with it again
    fileData = reader.nextLine();
        
    /* Prompt User for input. 
       - If nothing is entered for either the first name and the
         last name then all records are to be considered 'found'.
        
       - If nothing is provided for the first name and a last name
         is provided then all records containig that last name are
         considered as 'found'.
        
       - If the first name is provided but the last name is not 
         provided then all records containing that first name are
         considered as 'found'.
        
       - If the first name is provided and the last name is provided
         then all records containing that first name and that last 
         name are considered as 'found'.                        */
    System.out.print("Enter first name: --> ");
    String fName = userInput.nextLine().trim();
    System.out.print("Enter last name: --> ");
    String lName = userInput.nextLine().trim();
        
    /* Use an ArrayList or List Interface object to hold any 
       found records. Use this because a List can grow dynamically  */
    List<String> foundRecords = new ArrayList<>(); 
    boolean found = false;
    while (reader.hasNextLine()) {
        fileData = reader.nextLine().trim();
        // Skip blank lines (if any).
        if (fileData.isEmpty()) {
            continue;
        }
            
        /* The 'Regular Expression' (regex) to use in the String#split() method.
           This will handle any spacing around the comma delimiter when splitting.
           This eliminate the need to carry out array element trimming of leading 
           or trailing whitespaces.                                            */
        String regex = "\s*,\s*";
        String[] lineParts = fileData.split(regex);
        /* Based on the header line information we know that First Name 
           data is going to be in column index 0 and the Last Name data 
           is going to be in column index 1.                  */
        found = (fName.isEmpty() && lName.isEmpty()) ||
                (lineParts[0].equalsIgnoreCase(fName) && lName.isEmpty()) ||
                (fName.isEmpty() && lineParts[1].equalsIgnoreCase(lName)) || 
                (lineParts[0].equalsIgnoreCase(fName) && lineParts[1].equalsIgnoreCase(lName));
        if (found) {
            foundRecords.add(fileData);
            found = false;
        }
    }
        
    // Display found records (if any)
    System.out.println(); 
    System.out.println("Found Records:");
    System.out.println("====================================");
    if (foundRecords.isEmpty()) {
        System.out.println("         No Records Found!"); 
    }
    else {
        for (String str : foundRecords) {
            System.out.println(str); 
        }
    }
    System.out.println("====================================");
}
catch (FileNotFoundException ex) {
    Logger.getLogger("Method Has An Error!").log(Level.SEVERE, null, ex);
}

如果我使用以下数据创建一个名为 data.csv 的文本文件(文件 有一个 header 行 - 代码总是假设有一个):

First Name, Last Name, Age, Employee ID
Jack,       Flash,     32,  10000
Bob,        Smith,     27,  10008
Willy,      Wonka,     54,  11023
Sam,        Smith,     82,  13001
Betty,      Boop,      55,  10044 

然后在控制台中 window 我输入:

Enter first name: --> 
Enter last name: --> smith

控制台Window将显示:

Found Records:
====================================
Bob,        Smith,     27, 10008
Sam,        Smith,     82, 13001
====================================