1

How to read the CSV file in Java?

I assume I need to use an InputStream. How do I continue after the InputStream declaration?

InputStream file = item.getInputStream();
Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
nubteens
  • 5,462
  • 4
  • 20
  • 31
  • 1
    Does this answer your question? [Read all lines with BufferedReader](https://stackoverflow.com/questions/28977308/read-all-lines-with-bufferedreader) – Ivan Nov 21 '20 at 23:20

3 Answers3

5

For reading the CSV file, you can use the BufferedReader class:

BufferedReader reader = new BufferedReader(
    new InputStreamReader(new FileInputStream("CSV file location"))
);

After that, use StringTokenizer to read each common separated values from the file, ex.:

if(reader.readLine()!=null) {
    StringTokenizer tokens = new StringTokenizer(

    // this will read first line and separates values by (,) and stores them in tokens.
    (String) reader.readLine(), ",");

    tokens.nextToken(); // this method will read the tokens values on each call.
}

For example, the CSV file is having record of a employee, like:

ram,101
  • The first time, the tokens.nextToken() call will return ram.
  • The second time, the tokens.nextToken() call will return 101.
spenibus
  • 4,339
  • 11
  • 26
  • 35
  • This works considering that I am using the using a directory in my computer. However, I want is file upload but `BufferedReader reader = new BufferedReader(new InputStreamReader(file));` doesn't seem to work as I am getting an error in this line `List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);` – nubteens Oct 07 '15 at 07:54
0

For reading/manipulating csv in Java, you can check out Apache POI Library.

Xoul
  • 359
  • 1
  • 3
  • 13
0

I recommend https://commons.apache.org/proper/commons-csv/

"Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format."

salyh
  • 2,095
  • 1
  • 17
  • 31