I am facing a problem reading my CSV file with Java.
The java code I am using to read the CSV file is:
package collectData;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class testCSV {
public static void main(String[] args) throws IOException {
String csvFilePath = "csv_files\\20240403_OV64E_A.csv";
Charset encoding = Charset.forName("ISO-8859-1");
try (Reader in = new FileReader(csvFilePath, encoding);
CSVParser parser = CSVFormat.DEFAULT.withHeader().withDelimiter(';').parse(in)) {
for (CSVRecord record : parser) {
for (String headerName : parser.getHeaderNames()) {
System.out.print(headerName + ": " + record.get(headerName) +" ");
}
System.out.println();
}
}
}
}
When I try to read the file as it is downloaded, I get this error message:
Exception in thread "main" java.lang.IllegalArgumentException: A header name is missing in [Ref file, Version file, state file, App name, App version, APPS Classification, Apps release date, Data ref, Data version, DATA Classification, ]
at org.apache.commons.csv.CSVParser.createHeaders(CSVParser.java:509)
at org.apache.commons.csv.CSVParser.<init>(CSVParser.java:438)
at org.apache.commons.csv.CSVParser.<init>(CSVParser.java:404)
at org.apache.commons.csv.CSVFormat.parse(CSVFormat.java:1781)
at collecteRCD.testCSV.main(testCSV.java:28)
When I open the CSV file and I save it without modifying anything, the program works perfectly.
I tried to read the file with a text editor before and after I save it, and this is what changes:
Before:
Ref file;Version file;state file;App name;App version;APPS Classification;Apps release date;Data ref;Data version;DATA Classification;
003298;4.1;Figée;;;;;
003798;6.1;Figée;;;;;
After:
Ref file;Version file;state file;App name;App version;APPS Classification;Apps release date;Data ref;Data version;DATA Classification
3298;4.1;Figée;;;;;;;;
3798;6.1;Figée;;;;;;;;
I need to know a method to correct the CSV file automatically, because I am trying to build an automation app and it's pointless to keep correcting the files manually by opening them and saving them.
I looked online for some solutions but found nothing.
;