You should use the excellent OpenCSV for reading and writing CSV files. To adapt your example to use the library it would look like this:

public class ParseCSV {
  public static void main(String[] args) {
    try {
      //csv file containing data
      String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
      CSVReader reader = new CSVReader(new FileReader(strFile));
      String [] nextLine;
      int lineNumber = 0;
      while ((nextLine = reader.readNext()) != null) {
        lineNumber++;
        System.out.println("Line # " + lineNumber);

        // nextLine[] is an array of values from the line
        System.out.println(nextLine[4] + "etc...");
      }
    }
  }
}
Answer from Jason Sperske on Stack Overflow
Top answer
1 of 8
54

You should use the excellent OpenCSV for reading and writing CSV files. To adapt your example to use the library it would look like this:

public class ParseCSV {
  public static void main(String[] args) {
    try {
      //csv file containing data
      String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
      CSVReader reader = new CSVReader(new FileReader(strFile));
      String [] nextLine;
      int lineNumber = 0;
      while ((nextLine = reader.readNext()) != null) {
        lineNumber++;
        System.out.println("Line # " + lineNumber);

        // nextLine[] is an array of values from the line
        System.out.println(nextLine[4] + "etc...");
      }
    }
  }
}
2 of 8
13

Reading a CSV file in very simple and common in Java. You actually don't require to load any extra third party library to do this for you. CSV (comma separated value) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g comma ",").

In order to read specific columns from the CSV file, there are several ways. Simplest of all is as below:

Code to read CSV without any 3rd party library

BufferedReader br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
    // use comma as separator
    String[] cols = line.split(cvsSplitBy);
    System.out.println("Coulmn 4= " + cols[4] + " , Column 5=" + cols[5]);
}

If you notice, nothing special is performed here. It is just reading a text file, and spitting it by a separator – ",".

Consider an extract from legacy country CSV data at GeoLite Free Downloadable Databases

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"

Above code will output as below:

Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "TH" , Column 5="Thailand"

You can, in fact, put the columns in a Map and then get the values simply by using the key.

Shishir

🌐
Quora
quora.com › How-can-I-read-a-particular-column-of-a-particular-row-of-a-CSV-file-in-Java
How to read a particular column of a particular row of a CSV file in Java - Quora
Answer (1 of 4): Try this, see if it fits you needs. [code]BufferedReader br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { // use comma as separator String[] cols = line.split("|"); System.out.println("Coulmn 4= " + cols[4] + " , Column 5=" +...
Discussions

Read column wise in csv file using java
I have a csv file.I want to read my csv file and store it in a seperate array using java. ID Name 1 ramesh 2 rani 3 rahane 4 raja public static void main(String[] args) throws IOException { ArrayL More on c-sharpcorner.com
🌐 c-sharpcorner.com
java - How to read specific columns from CSV file? - Stack Overflow
2 how to read a specific column of tab separated csv file and parse all row values of a particular column value More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
iteration - How to read a specific column of a row from a csv file in java - Stack Overflow
I have the following code which reads the data from the csv file, it iterates over the rows but i don't manage to figure out how to iterate over specific columns (for example the first 2 columns of... More on stackoverflow.com
🌐 stackoverflow.com
Reading a column from CSV file using JAVA - Stack Overflow
Sure it seems easy, Each line is a row, each comma is a column. That is true until its not! Take a look at opencsv.sourceforge.net or one of the other library out there. It will take the pain away from maintaining a proper csv format. ... For the record it is Java, not JAVA. More on stackoverflow.com
🌐 stackoverflow.com
November 12, 2013
🌐
Thoughtcoders
thoughtcoders.com › blogs › how-to-read-csv-file-column-by-column-using-java
How To Read CSV File Column By Column Using Java
BHIVE Premium Whitefield Campus, Plot No. 77, JBR Tech Park, 6th Rd, Whitefield, EPIP Zone, Whitefield, Bengaluru, Karnataka 560066 · Email: info@thoughtcoders.com
🌐
Java67
java67.com › 2015 › 08 › how-to-load-data-from-csv-file-in-java.html
How to load data from CSV file in Java - Example | Java67
We take the string that we read from the CSV file and split it up using the comma as the 'delimiter' (because it's a CSV file). This creates an array with all the columns of the CSV file as we want, however, values are still in Strings, so we ...
🌐
CodingTechRoom
codingtechroom.com › question › read-column-csv-java
How to Read a Specific Column from a CSV File Using Java? - CodingTechRoom
import java.io.*; import java.nio.file.*; import java.util.*; public class CSVReader { public static void main(String[] args) { String path = "path/to/your/file.csv"; int columnIndex = 2; // Index of the column to read List<String> columnData = readCsvColumn(path, columnIndex); System.out....
🌐
C# Corner
c-sharpcorner.com › forums › read-column-wise-in-csv-file-using-java
Read column wise in csv file using java
I have a csv file.I want to read my csv file and store it in a seperate array using java. ID Name 1 ramesh 2 rani 3 rahane 4 raja public static void main(String[] args) throws IOException { ArrayL...
🌐
Stack Overflow
stackoverflow.com › questions › 21113865 › how-to-read-specific-columns-from-csv-file
java - How to read specific columns from CSV file? - Stack Overflow
May 22, 2017 - Using Commons CSV you can iterate over the csv elements and read the specific column using the column label.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 70586145 › how-to-read-a-specific-column-of-a-row-from-a-csv-file-in-java
iteration - How to read a specific column of a row from a csv file in java - Stack Overflow
String file = "pathToCsvFile"; BufferedReader reader = null; String line = ""; try { reader = new BufferedReader(new FileReader(file)); while((line = reader.readLine()) != null) { String[] row = line.split(","); for(String index:row) { //HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW } } } catch(Exception e) { e.printStackTrace(); } finally { try { reader.close(); } catch(IOException e) { e.printStackTrace(); } } ... Note that this is a very naive way to properly read a CSV.
Top answer
1 of 3
2

I don't think you can read specific column.Better to read entire row using CSVParser or you can read CSV line by line and split it and get String array then you can get specific column but yes you need to read whole row gain.

Try it.

    String fName = "C:\\Amit\\abc.csv";
    String thisLine;
    int count = 0;
    FileInputStream fis = new FileInputStream(fName);
    DataInputStream myInput = new DataInputStream(fis);
    int i = 0;
    while ((thisLine = myInput.readLine()) != null) {
        String strar[] = thisLine.split(",");
            System.out.println(strar[3]);
                        // Here column 2
        }
    }

By this way you can read specific column.

2 of 3
0

I had a similar problem in Objective C the other day, but this is how I solved it.

This method assumes you know the column number of the data you want. (I.E. if you want column 1 of 6)

Read all the rows into strings and append them into one.

Data sample: (columns 1 to 6)

1,2,3,4,5,6
13,45,63,29,10,8
11,62,5,20,13,2

String 1 = 1,2,3,4,5,6

String 2 = 13,45,63,29,10,8

String 3 = 11,62,5,20,13,2

Then you should get this:

String combined = 1,2,3,4,5,6,13,45,63,29,10,8,11,62,5,20,13,2 //add in the missing "," when you concatenate strings

Next you need to split the string into an array of all values.

Use code somewhat like this: (written off the top of my head so may be off.)

String[] values = combined.split(",");  

Now you should have something like this:

Values = `"1", "2", "3", ... etc`

The last step is to loop through the entire array and modulo for whatever column you need:

//Remember that java numbers arrays starting with 0.
//The key here is that all remainder 0 items fall into the first column.  All remainder 1 items fall into the second column.  And so on.

    for(int i = 0; i < values.length(); i++)
    {
            //Column1 - Column6 -> array lists of size values.length/number of columns
            //In this case they need to be size values.length/6
        if(i % 6 == 0)
            column1.add(values[i]);
        else if(i % 6 == 1)
            column2.add(values[i]);
        else if(i % 6 == 2)
            column3.add(values[i]);
        else if(i % 6 == 3)
            column4.add(values[i]);
        else if(i % 6 == 4)
            column5.add(values[i]);
        else if(i % 6 == 5)
                column6.add(values[i]);

    }

~~~~~~~~~~~~~~~~

Edit:

You added code to your question. Above I was saving them into memory. You just loop through and print them out. In your while loop, split each line separately into an array and then either hardcode the column number or modulo the length of the array as the index.

🌐
Mkyong
mkyong.com › home › java › how to read and parse csv file in java
How to read and parse CSV file in Java - Mkyong.com
December 26, 2020 - Talks about CSV file parsing, RFC 4180, OpenCSV and Single class implementation examples to read and parse a CSV file.
🌐
Attacomsian
attacomsian.com › blog › java-read-parse-csv-file
How to read and parse a CSV file in Java
September 24, 2022 - You can either use the BufferedReader class or the Scanner class to easily read the file in Java. Since CSV is just a plain-text file, the BufferedReader class can be used to read it line by line.
Top answer
1 of 2
1

If your CSV file(s) always contains a Header Line which indicates the Table Column Names then it's just a matter of catching this line and splitting it so as to place those column names into a String Array (or collection, or whatever). The length of this array determines the amount of data expected to be available for each record data line. Once you have the Column Names it's gets relatively easy from there.

How you acquire your CSV file path and it's format type is obviously up to you but here is a general concept how to carry out the task at hand:

public static void readCsvToConsole(String csvFilePath, String csvDelimiter) {
    String line;                            // To hold each valid data line.
    String[] columnNames = new String[0];   // To hold Header names.
    int dataLineCount = 0;                  // Count the file lines.
    StringBuilder sb = new StringBuilder(); // Used to build the output String.
    String ls = System.lineSeparator();     // Use System Line Seperator for output.

    // 'Try With Resources' to auto-close the reader
    try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
        while ((line = br.readLine()) != null) {
            // Skip Blank Lines (if any).
            if (line.trim().equals("")) {
                continue;
            }
            dataLineCount++;
            // Deal with the Header Line. Line 1 in most CSV files is the Header Line.
            if (dataLineCount == 1) {
                /* The Regular Expression used in the String#split()
                   method handles any delimiter/spacing situation.*/
                columnNames = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
                continue;   // Don't process this line anymore. Continue loop.
            }
            // Split the file data line into its respective columnar slot.
            String[] lineParts = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
            /* Iterate through the Column Names and buld a String
               using the column names and its' respective data along
               with a line break after each Column/Data line.     */
            for (int i = 0; i < columnNames.length; i++) {
                sb.append(columnNames[i]).append(": ").append(lineParts[i]).append(ls);
            }
            // Display the data record in Console.
            System.out.println(sb.toString());  
            /* Clear the StringBuilder object to prepare for 
               a new string creation.     */
            sb.delete(0, sb.capacity());        
        }
    }
    // Trap these Exceptions
    catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }
    catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
}

With this method you can have 1 to thousands of columns, it doesn't matter (not that you would ever have thousands of data columns in any given record but hey....you never know... lol). And to use this method:

// Read CSV To Console Window.
readCsvToConsole("test.csv", ",");
2 of 2
0

Here is some code that I recently worked on for an interview that might help: https://github.com/KemarCodes/ms3_csv/blob/master/src/main/java/CSVProcess.java

If you always have 3 attributes, I would read the first line of the csv and set values in an object that has three fields: attribute1, attribute2, and attribute3. I would create another class to hold the three values and read all the lines after, creating a new instance each time and reading them in an array list. To print I would just print the values in the attribute class each time alongside each set of values.

Top answer
1 of 3
1

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.

2 of 3
1

Below function will Read column name as parameter and output Valid if Column is Not empty and Invalid if column is empty


Input as in csv file

HEADER1;HEADER2;HEADER3;
A;;C;
D;E;F;

Solution:

public String fun(String col) throws IOException {
    String[] array = null;
    int Colx = -1; //Colx  is Column index
    File file = new File("test.csv");
    List < String > lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); //reads all lines

    for (String line: lines) {

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

        if (Colx != -1) { //Except first Row
            if (array[Colx].equals("")) { // and only Empty columns  
                return "Invalid";
            }
        } else { //only for first row // finding index of column matched

            for (String ar: array) {
                Colx++;
                if (ar.equalsIgnoreCase(col)) {
                    break;
                }
            }
        }
    }
    return "Valid"; //if Everything went well 
}
🌐
How to do in Java
howtodoinjava.com › home › i/o › parse and read a csv file in java
Parse and Read a CSV File in Java
September 14, 2022 - In Java, there are different ways of reading and parsing CSV files. Let's discuss some of the best approaches such as OpenCSV, Super CSV etc.
🌐
How to do in Java
howtodoinjava.com › home › java libraries › super csv – read and write csv files in java
Super CSV - Read and Write CSV Files in Java
October 1, 2022 - So you read all columns in a row in a List and then based on the size of the list, you determine how you may want to handle the read values. Let’s modify the data.csv and remove some data from it randomly. CustomerId,CustomerName,Country,PinCode,Email 10001,Lokesh,India,110001,abc@gmail.com 10002,John,USA 10003,Blue,France,330003 · Let’s read this CSV file. import java.io.FileReader; import java.io.IOException; import java.util.List; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.ParseLong; import org.supercsv.cell
🌐
CodeJava
codejava.net › coding › super-csv-reading-csv-files-into-pojos-with-csvbeanreader
Java Reading CSV File Example with Super CSV
package net.codejava.supercsv; import java.util.Date; public class Book { private String isbn; private String title; private String author; private String publisher; private Date published; private double price; public Book() { // this empty constructor is required } public Book(String isbn, String title, String author, String publisher, Date published, double price) { this.isbn = isbn; this.title = title; this.author = author; this.publisher = publisher; this.published = published; this.price = price; } // getters and setters }This POJO class defines fields that match the column headers in the CSV file. Remember to supply complete code for the getters and setters. Super CSV provides some classes called cell processors that automate data type conversions and enforce constraints when mapping values in the CSV file with JavaBean’s properties.
🌐
Scaler
scaler.com › home › topics › how to read csv file in java?
How to Read CSV File in Java?- Scaler Topics
January 13, 2024 - Firstly, include the OpenCSV dependency in the project to import necessary classes for reading the file. read CSV file in Java and handle exceptions that may be thrown. In CSV files the column data is separated by commas (commas as delimiter) ...
🌐
Freelancer
freelancer.com › job search › how to read a particular column from csv file in java › 40
How to read a particular column from csv file in java Jobs, Employment | Freelancer
For now I’d like the app to detect or gracefully ask whether the file is SQL, CSV, or JSON, then continue. 2. Parse: every table (or top-level JSON array / CSV sheet) is listed, with a quick preview so the user can deselect anything they don’t need. 3. Export: one click should create a new Google S... Android API Development Database Management Flutter JavaScript Mobile App Development PHP Web Development