How to Read CSV Using Column Name in Java

Question

Source:https://stackoverflow.com/questions/59306694/how-to-read-csv-using-column-name-in-java

I have tried reading a column with its index using the following code:

int col1;

String msg = null;

int i = 0;

String[] array = null;

File file = new File(csvFileName);

List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

for (String line : lines) {

array = line.split(";", -1);

// System.out.println(array[col1]);

if (array[col1].equals("")) {

// System.out.println("Cell is blank");

break;

} else {

// System.out.println(array[col1].toString());

i++;

}

}

if (i < (array[col1].length())) {

msg = "Invalid file";

// System.out.println("Invalid File");

} else {

msg = "Valid file";

// System.out.println("valid File");

}

return msg;

for eg.

|HEADER 1| HEADER 2| HEADER 3|

|A|B|C|

|D| |F|

I am passing col index in col1, but I am not able to store the column header text in variable to print that which column is having blank value.

Is there any way I can read the column to validate blank cells and then print the column name in result saying "This column is having blank cell and hence file is invalid".

In above table, how to read columns with its name. Say, if I pass HEADER 2 it should read all the row data and if it finds blank field.

Answer

To get names of columns containing blank values in Java, the code will be rather long.

You can use SPL, the open-source Java package, to accomplish this. It is easy and only one line of code is enough:

A

1

=transpose(file("data.csv").import@w(;,";")).select(~.contain(null)).(~(1)/",This   column is having blank cell and hence file is invalid")

 

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as validate.splx and invoke it in Java as you call a stored procedure:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call validate()");
st.execute();

View SPL source code.