24

Hi I am trying to read a CSV File called test.csv in JAVA . Below is my code :

import java.io.BufferedReader;
import java.io.FileReader;

public class InsertValuesIntoTestDb {

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) throws Exception {
                String splitBy = ",";
        BufferedReader br = new BufferedReader(new FileReader("test.csv"));
        String line = br.readLine();
        while(line!=null){
             String[] b = line.split(splitBy);
             System.out.println(b[0]);
        }
        br.close();

  }
}

This is my CSV File (test.csv):

a,f,w,b,numinst,af,ub
1RW,800,64,22,1,48:2,true
1RW,800,16,39,1,48:2,true
1RW,800,640,330,1,48:2,true
1RW,800,40,124,1,48:2,true
1RW,800,32,104,1,48:2,true
1RW,800,8,104,1,48:2,true
1R1W,800,65536,39,1,96:96,true
1R1W,800,2048,39,1,96:96,true
1R1W,800,8192,39,1,48:48,true

I am trying to print the first column in the csv ,but the output I get is only a in an infinite loop . Can anyone please help me fix this code to print the entire first column. Thanks.

Newbie
  • 2,664
  • 7
  • 34
  • 75
  • 2
    You don't reassign `line` in the loop, so the code loops until line is `null` which will never occour. – Andre Nov 12 '13 at 14:33
  • 1
    Just a note that hopefully helps you survive some of the pain and suffering that some of us have been through. Don't write custom parsers and writers for csv... Sure it seems easy, Each line is a row, each comma is a column. That is true until its not! Take a look at http://opencsv.sourceforge.net/ or one of the other library out there. It will take the pain away from maintaining a proper csv format. – buzzsawddog Nov 12 '13 at 14:38
  • 1
    For the record it is Java, not JAVA. – Jax Dec 16 '15 at 16:36

4 Answers4

19

Read the input continuously within the loop so that the variable line is assigned a value other than the initial value

while ((line = br.readLine()) !=null) {
  ...
}

Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files

Reimeus
  • 158,255
  • 15
  • 216
  • 276
18

If you are using Java 7+, you may want to use NIO.2, e.g.:

Code:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

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

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • `List lines = Files.readAllLines()` good one +1 – atish shimpi Feb 04 '15 at 07:52
  • 2
    This doesn't work when the columns contain commas – OneCricketeer Apr 05 '17 at 23:34
  • @cricket_007 why is it? he is doing split with comma –  Mar 20 '18 at 11:49
  • @Sha You've clearly never worked with a CSV that contained a list of data within a single column if you don't understand that splitting on just any random comma is not a solution. I understand the question itself is asking for only the first column and the sample data given does not have extra commas itself. However, people are coming here to "parse CSV in Java", and this answer is flawed – OneCricketeer Mar 20 '18 at 13:20
  • @cricket_007 oh u r talking about comma sperated values in one column? , then i m misunderstood –  Mar 20 '18 at 13:27
  • @Paul Vargas in the line: List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); where is the reference to `Files` – Gunasekar Sep 29 '18 at 05:28
  • @Gunasekar [`java.nio.file.Files`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html), since Java 7. – Paul Vargas Sep 29 '18 at 22:53
16

Splitting by comma doesn't work all the time for instance if you have csv file like

"Name" , "Job" , "Address"
"Pratiyush, Singh" , "Teacher" , "Berlin, Germany"

So, I would recommend using the Apache Commons CSV API:

    Reader in = new FileReader("input1.csv");
    Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
    for (CSVRecord record : records) {
      System.out.println(record.get(0));
    }
Bit33
  • 338
  • 1
  • 9
Pratiyush Kumar Singh
  • 1,977
  • 3
  • 19
  • 39
3

You are not changing the value of line. It should be something like this.

import java.io.BufferedReader;
import java.io.FileReader;

public class InsertValuesIntoTestDb {

  @SuppressWarnings("rawtypes")
  public static void main(String[] args) throws Exception {
      String splitBy = ",";
      BufferedReader br = new BufferedReader(new FileReader("test.csv"));
      while((line = br.readLine()) != null){
           String[] b = line.split(splitBy);
           System.out.println(b[0]);
      }
      br.close();

  }
}

readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.

Matt Rink
  • 345
  • 2
  • 12