读取两个逗号分隔文件并对比行内容的技术实现需求
Alright, let's break down how to solve this problem. You need to read two CSV files (each line has 4 comma-separated elements), compare their contents, and identify three types of differences: lines only in the first file, lines only in the second file, and lines where one or more elements differ (but share a unique identifier like student ID). Let's build on your existing Student class and add all the necessary logic.
Step 1: Complete the Student Class
First, we'll expand the Student class to hold all four elements, add a method to convert CSV lines to Student objects, and override equals()/hashCode() so we can properly compare student records.
import java.util.Objects; public class Student { public String name; public String id; // Assuming this is the unique identifier public String major; public String grade; public Student(String name, String id, String major, String grade) { this.name = name; this.id = id; this.major = major; this.grade = grade; } // Convert a single CSV line to a Student object public static Student fromCsvLine(String line) { // Split into exactly 4 parts (handles cases where fields might have leading/trailing spaces) String[] parts = line.split(",", 4); if (parts.length != 4) { throw new IllegalArgumentException("Invalid line format: " + line); } return new Student( parts[0].trim(), parts[1].trim(), parts[2].trim(), parts[3].trim() ); } // Override to compare all fields for equality @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(name, student.name) && Objects.equals(id, student.id) && Objects.equals(major, student.major) && Objects.equals(grade, student.grade); } // Override hashCode to match equals() @Override public int hashCode() { return Objects.hash(name, id, major, grade); } // For easy printing of student details @Override public String toString() { return String.format("%s, %s, %s, %s", name, id, major, grade); } }
Step 2: Read Files into a Map
We'll use a Map keyed by the student ID to easily look up records across both files. This helps us quickly find matching IDs and compare their other fields.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class StudentFileComparator { private static Map<String, Student> readStudentsToMap(String filePath) throws IOException { Map<String, Student> studentMap = new HashMap<>(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { if (!line.isBlank()) { // Skip empty lines to avoid errors Student student = Student.fromCsvLine(line); studentMap.put(student.id, student); } } } return studentMap; }
Step 3: Compare Files and Identify Differences
Now we'll write the core comparison logic to find all three types of differences:
public static void compareStudentFiles(String file1Path, String file2Path) throws IOException { Map<String, Student> file1Students = readStudentsToMap(file1Path); Map<String, Student> file2Students = readStudentsToMap(file2Path); // 1. Lines only present in the first file System.out.println("=== Records only in first file ==="); for (String id : file1Students.keySet()) { if (!file2Students.containsKey(id)) { System.out.println(file1Students.get(id)); } } // 2. Lines only present in the second file System.out.println("\n=== Records only in second file ==="); for (String id : file2Students.keySet()) { if (!file1Students.containsKey(id)) { System.out.println(file2Students.get(id)); } } // 3. Records with the same ID but different details System.out.println("\n=== Records with matching IDs but differing details ==="); for (String id : file1Students.keySet()) { if (file2Students.containsKey(id)) { Student s1 = file1Students.get(id); Student s2 = file2Students.get(id); if (!s1.equals(s2)) { System.out.println("First file: " + s1); System.out.println("Second file: " + s2); System.out.println("---"); } } } } // Main method to run the comparison public static void main(String[] args) { try { // Replace with your actual file paths compareStudentFiles("students_file1.csv", "students_file2.csv"); } catch (IOException e) { System.err.println("Error reading files: " + e.getMessage()); e.printStackTrace(); } } }
Key Notes
- Unique Identifier: We assumed the second element is a unique student ID. If your unique field is different (e.g., name), just adjust the
Mapkey to use that field instead. - CSV Handling: This uses a simple
splitfor CSV parsing. If your files have fields containing commas (enclosed in quotes), you'll want to use a dedicated CSV library instead of manual splitting. - Error Handling: The code includes basic error handling for invalid lines and file reading issues, but you can expand this as needed for your use case.
内容的提问来源于stack exchange,提问作者Jo An

