Skip to content
Advertisement

How to read csv using column name in java

I have tried reading a column with its index using below 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|

As 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

Advertisement

Answer

According to your input data example:

|HEADER 1| HEADER 2| HEADER 3|
|A|B|C|
|D| |F|

So you have a file composed from ha header line, where you have your column names, and the data.

To read the colimns name you need to parse the first row differently:

// field separator
String separator = ";";

//...
int i = 0;

Map<String, int> headers = new HashMap<>();

for (String line : lines) {
    if (i == 0) {
        String[] headLine = line.split(separator);
        for (int j = 0; j < headLine.length; j++) {
            headLine.put(headLine[j], j);
        }
        i++;
        continue;
    }
}

So you put each column name in your map and you save the index of the column.

The size of the map it is also the row len to check if you read all the expected fields.

Then you read the data:

int col1 = 1; // assign a valid column index
int fields = 0;

for (String line : lines) {

    if (array[col1].equals("")) {
        // System.out.println("Cell is blank");
        break;
    } else {
        // System.out.println(array[col1].toString());
        fields++;
    }
}

if (fields < headers.size()) {
    msg = "Invalid file";
    // headers[fields] is the name of the column with the empty cell 
}

In your example col1 is the index not the name of the column, but you never set it with a value, maybe this is one of the issues.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement