Compare two files
Testing code
Try this
workigng code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataComparator {
public static void main(String[] args) {
// Step 1: Parse cbf.txt and store data in HashMap
Map<String, List<String>> cbfData = parseFile("C:\\Users\\Nildip\\.eclipse\\datacomparison\\data\\cbf_file.txt", 39, 56);
// Step 2: Parse akora.txt and store data in HashMap
Map<String, List<String>> akoraData = parseFile("C:\\Users\\Nildip\\.eclipse\\datacomparison\\data\\Akora_file.txt", 39, 56);
// Step 3: Compare data and generate result lists
List<String> updatedList = new ArrayList<>();
List<String> deletedList = new ArrayList<>();
List<String> newList = new ArrayList<>();
for (Map.Entry<String, List<String>> entry : akoraData.entrySet()) {
String primaryKey = entry.getKey();
List<String> akoraValues = entry.getValue();
List<String> cbfValues = cbfData.get(primaryKey);
if (cbfValues != null) {
// Data exists in both files
if (!akoraValues.equals(cbfValues)) {
// Data is different, consider it as updated
updatedList.add(primaryKey);
}
} else {
// Data exists only in akora.txt, consider it as new
newList.add(primaryKey);
}
}
// Check for deleted data in cbfData
for (String primaryKey : cbfData.keySet()) {
if (!akoraData.containsKey(primaryKey)) {
// Data exists in cbf.txt but not in akora.txt, consider it as deleted
deletedList.add(primaryKey);
}
}
// Print the result lists
System.out.println("Updated List: " + updatedList);
System.out.println("Deleted List: " + deletedList);
System.out.println("New List: " + newList);
}
private static Map<String, List<String>> parseFile(String filename, int start, int end) {
Map<String, List<String>> dataMap = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
String primaryKey = line.substring(start - 1, end).trim();
List<String> values = parseData(line);
dataMap.put(primaryKey, values);
}
} catch (IOException e) {
e.printStackTrace();
}
return dataMap;
}
private static List<String> parseData(String line) {
// Customize this method based on the structure of your data
List<String> values = new ArrayList<>();
// Add logic to extract data based on indices
// For example:
values.add(line.substring(0, 10).trim());
values.add(line.substring(10, 20).trim());
// Add more lines according to your data structure
return values;
}
}
https://copyprogramming.com/howto/java-comparing-two-csv-files-in-java
To compare two CSV files in Java, one solution is to use a specialized CSV parsing library to increase efficiency. Initially, we can read one of the CSV files and produce a Map using the following code. Once we have the map with records, we can compare the second file and create a new one with any modifications detected. This approach should be effective.
import java.io.*;
import java.util.ArrayList;
/* file1 - file2 = file3*/
public class CompareCSV {
public static void main(String args[]) throws FileNotFoundException, IOException
{
String path="D:\\csv\\";
String file1="file1.csv";
String file2="file2.csv";
String file3="p3lang.csv";
ArrayList al1=new ArrayList();
ArrayList al2=new ArrayList();
//ArrayList al3=new ArrayList();
BufferedReader CSVFile1 = new BufferedReader(new FileReader(path+file1));
String dataRow1 = CSVFile1.readLine();
while (dataRow1 != null)
{
String[] dataArray1 = dataRow1.split(",");
for (String item1:dataArray1)
{
al1.add(item1);
}
dataRow1 = CSVFile1.readLine(); // Read next line of data.
}
CSVFile1.close();
BufferedReader CSVFile2 = new BufferedReader(new FileReader(path+file2));
String dataRow2 = CSVFile2.readLine();
while (dataRow2 != null)
{
String[] dataArray2 = dataRow2.split(",");
for (String item2:dataArray2)
{
al2.add(item2);
}
dataRow2 = CSVFile2.readLine(); // Read next line of data.
}
CSVFile2.close();
for(String bs:al2)
{
al1.remove(bs);
}
int size=al1.size();
System.out.println(size);
try
{
FileWriter writer=new FileWriter(path+file3);
while(size!=0)
{
size--;
writer.append(""+al1.get(size));
writer.append('\n');
}
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}}
Java code please
Certainly! Here's a simple Java example for comparing two CSV files based on a primary key:
javaCopy codeimport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CSVComparator {
public static void main(String[] args) {
String file1Path = "file1.csv";
String file2Path = "file2.csv";
int primaryKeyIndex = 0; // Assuming the primary key is in the first column
try {
Map<String, String[]> dataMap1 = readCSV(file1Path, primaryKeyIndex);
Map<String, String[]> dataMap2 = readCSV(file2Path, primaryKeyIndex);
// Compare the two maps based on primary keys
for (String key : dataMap1.keySet()) {
if (dataMap2.containsKey(key)) {
if (!Arrays.equals(dataMap1.get(key), dataMap2.get(key))) {
System.out.println("Lines with key " + key + " differ:");
System.out.println("File 1: " + Arrays.toString(dataMap1.get(key)));
System.out.println("File 2: " + Arrays.toString(dataMap2.get(key)));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, String[]> readCSV(String filePath, int primaryKeyIndex) throws IOException {
Map<String, String[]> dataMap = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
String primaryKey = values[primaryKeyIndex];
dataMap.put(primaryKey, values);
}
}
return dataMap;
}
}
This Java code assumes that the CSV files have a simple structure with comma-separated values and that the primary key is in the first column (index 0). Adjust the primaryKeyIndex
parameter if your primary key is in a different column. Additionally, you may need to handle variations in CSV file formats based on your specific use case.
You
Primary is in the middle of the line some where. from character 21 to 34
If the primary key is in the middle of the line, and its location is determined by character positions (from 21 to 34 in your case), you can modify the Java code accordingly. Here's an updated example:
javaCopy codeimport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CSVComparator {
public static void main(String[] args) {
String file1Path = "file1.csv";
String file2Path = "file2.csv";
try {
Map<String, String[]> dataMap1 = readCSV(file1Path, 21, 34);
Map<String, String[]> dataMap2 = readCSV(file2Path, 21, 34);
// Compare the two maps based on primary keys
for (String key : dataMap1.keySet()) {
if (dataMap2.containsKey(key)) {
if (!Arrays.equals(dataMap1.get(key), dataMap2.get(key))) {
System.out.println("Lines with key " + key + " differ:");
System.out.println("File 1: " + Arrays.toString(dataMap1.get(key)));
System.out.println("File 2: " + Arrays.toString(dataMap2.get(key)));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, String[]> readCSV(String filePath, int startIndex, int endIndex) throws IOException {
Map<String, String[]> dataMap = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String primaryKey = line.substring(startIndex - 1, endIndex);
String[] values = line.split(","); // Adjust if your CSV uses a different delimiter
dataMap.put(primaryKey, values);
}
}
return dataMap;
}
}
In this code, the readCSV
method now takes the start and end indices for the primary key as parameters. It uses substring
to extract the primary key from the specified character positions. Adjust the delimiter in the split
method if your CSV file uses a different separator.