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
🌐
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...
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

Discussions

java - How to read a CSV file column wise using hadoop? - Stack Overflow
Explore Stack Internal ... i am trying to read a csv file which does not contains coma separated values , these are columns for NASDAQ Stocks, i want to read a particular column, assume (3rd), do not know , how to get the column items. IS there any method to read Column wise data in hadoop? More on stackoverflow.com
🌐 stackoverflow.com
March 14, 2014
How to read specific columns in CSV file java - Stack Overflow
my CSV file looks like this: Id;date;code;type;category;name;position;formula 10;;;2010-02-01;;000010;P;W;NormalDays;10;#formelTest 55;;;2050-05-02;;000055;D;C;SpecificDays;55;#formelTest2 60;;;23... More on stackoverflow.com
🌐 stackoverflow.com
July 14, 2017
How to read data from a specific column from csv file using jsp/java? - Stack Overflow
In my application I need to read a specific column of tab separated csv file using jsp. But I can read the data of full row not a specific column. I need help this regard. Please help me Thanks ... 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. ... Read the input ... More on stackoverflow.com
🌐 stackoverflow.com
November 12, 2013
🌐
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=" +...
🌐
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
Find elsewhere
🌐
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
Effective Java,42,Joshua Bloch ... and how they are doing : To read the CSV file we are going to use a BufferedReader in combination with a FileReader....
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.

🌐
Stack Overflow
stackoverflow.com › questions › 60331510 › writing-appending-data-to-a-csv-file-column-wise-in-java
Writing/appending data to a CSV file, column wise, in JAVA - Stack Overflow
February 21, 2020 - So to write the data columnwise ... one line available on writing that line, or run through your csv file and it's lines several times, each time adding another item to a row....
🌐
Java2s
java2s.com › Questions_And_Answers › Java-File › CSV-file › read.htm
read « CSV file « Java I/O Q&A
I am writing a CSV exporter in Java that should respect the user's custom settings, especially the "List separator" to use as a delimiter. In Windows, one can set this List separator · at the moment I have this: import java.util.*; import java.io.*; import java.io.BufferedReader; import ...
🌐
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.
🌐
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....
🌐
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.
🌐
Blogger
javarevisited.blogspot.com › 2015 › 06 › 2-ways-to-parse-csv-files-in-java-example.html
2 Ways to Parse CSV Files in Java - BufferedReader vs Apache Commons CSV Example
August 7, 2021 - You open a CSV file and start reading it line by line, since each line contains a coma separated String, you need to split them using comma (",") and you will get an array of String containing each column.
🌐
Improbable-research
improbable-research.github.io › keanu › docs › data-io
Reading/Writing CSV - GitHub Pages
If you don’t feel like processing the raw lines from your CSV file, then you have the option to read directly to a Java object.