user3242329 user3242329 - 1 month ago 13
Java Question

How to compare the content (header) of a file with the defined variables in java and update in database?

I want the system to read the csv file in order to analyse the headers and rows of the csv file. The headers of csv file should match with the variables of ProductDetail.java. If the headers matches with these variables, then insert the rows that were read into the database under those headers.

ProductDetail.java

public class ProductDetail {
String street;
String city;

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}


ReadFile.java

public class ReadFile {
public static void main(String[] args) {
FileReader input = null;
BufferedReader br = null;

try {

input = new FileReader("uploadedFile.csv");
br = new BufferedReader(input);
String str;

while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
br.close();
}
catch (IOException x) {
x.printStackTrace();
}
}
}
}


I have started the project, but now I am quite stuck on how read the columns & rows and match with those predefined headers that are set in ProductDetail.java. It would be great if you can help me on this.

Answer

With SuperCSV, you can do that to validate that headers of the csv matches with the expected header. Generally, the expected header is fixed. So, you should write them as constant.

public static void main(String[] args) throws IOException {
CsvBeanReader csvBeanReader = null;
try {

    // your csv file
    String csvFile = null;
    csvBeanReader = new CsvBeanReader(csvFile), CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);

    final String[] headersArray = csvBeanReader.getHeader(true);
    List<String> headers = Arrays.asList(headersArray);
    List<String> expectedHeaders = Arrays.asList("street", "city");
    if (!expectedHeaders.equals(headers)) {
        return;
    }

    final CellProcessor[] processors = new CellProcessor[] { new NotNull(), new NotNull() };

    List<ProductDetail> productDetails = new ArrayList<>();
    ProductDetail productDetail = null;

    while ((productDetail = csvBeanReader.read(ProductDetail.class, headersArray, processors)) != null) {
      productDetails.add(productDetail);
    }
    // save products in your DB
}
finally {
    try {
      csvBeanReader.close();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
}
}