Please stop writing faulty CSV parsers!

I've seen hundreds of CSV parsers and so called tutorials for them online.

Nearly every one of them gets it wrong!

This wouldn't be such a bad thing as it doesn't affect me but people who try to write CSV readers and get it wrong tend to write CSV writers, too. And get them wrong as well. And these ones I have to write parsers for.

Please keep in mind that CSV (in order of increasing not so obviousness):

  1. can have quoting characters around values
  2. can have other quoting characters than "
  3. can even have other quoting characters than " and '
  4. can have no quoting characters at all
  5. can even have quoting characters on some values and none on others
  6. can have other separators than , and ;
  7. can have whitespace between seperators and (quoted) values
  8. can have other charsets than ascii
  9. should have the same number of values in each row, but doesn't always
  10. can contain empty fields, either quoted: "foo","","bar" or not: "foo",,"bar"
  11. can contain newlines in values
  12. can not contain newlines in values if they are not delimited
  13. can not contain newlines between values
  14. can have the delimiting character within the value if properly escaped
  15. does not use backslash to escape delimiters but...
  16. uses the quoting character itself to escape it, e.g. Frodo's Ring will be 'Frodo''s Ring'
  17. can have the quoting character at beginning or end of value, or even as only character ("foo""", """bar", """")
  18. can even have the quoted character within the not quoted value; this one is not escaped

If you think this is obvious not a problem, then think again. I've seen every single one of these items implemented wrongly. Even in major software packages. (e.g. Office-Suites, CRM Systems)

There are good and correctly working out-of-the-box CSV readers and writers out there:

  • opencsv
  • Ostermiller Java Utilities
  • Apache Commons CSV

If you insist on writing your own at least read the (very short) RFC for CSV.

Answer from Scheintod on Stack Overflow
Top answer
1 of 8
162

Please stop writing faulty CSV parsers!

I've seen hundreds of CSV parsers and so called tutorials for them online.

Nearly every one of them gets it wrong!

This wouldn't be such a bad thing as it doesn't affect me but people who try to write CSV readers and get it wrong tend to write CSV writers, too. And get them wrong as well. And these ones I have to write parsers for.

Please keep in mind that CSV (in order of increasing not so obviousness):

  1. can have quoting characters around values
  2. can have other quoting characters than "
  3. can even have other quoting characters than " and '
  4. can have no quoting characters at all
  5. can even have quoting characters on some values and none on others
  6. can have other separators than , and ;
  7. can have whitespace between seperators and (quoted) values
  8. can have other charsets than ascii
  9. should have the same number of values in each row, but doesn't always
  10. can contain empty fields, either quoted: "foo","","bar" or not: "foo",,"bar"
  11. can contain newlines in values
  12. can not contain newlines in values if they are not delimited
  13. can not contain newlines between values
  14. can have the delimiting character within the value if properly escaped
  15. does not use backslash to escape delimiters but...
  16. uses the quoting character itself to escape it, e.g. Frodo's Ring will be 'Frodo''s Ring'
  17. can have the quoting character at beginning or end of value, or even as only character ("foo""", """bar", """")
  18. can even have the quoted character within the not quoted value; this one is not escaped

If you think this is obvious not a problem, then think again. I've seen every single one of these items implemented wrongly. Even in major software packages. (e.g. Office-Suites, CRM Systems)

There are good and correctly working out-of-the-box CSV readers and writers out there:

  • opencsv
  • Ostermiller Java Utilities
  • Apache Commons CSV

If you insist on writing your own at least read the (very short) RFC for CSV.

2 of 8
48
scanner.useDelimiter(",");

This should work.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class TestScanner {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("/Users/pankaj/abc.csv"));
        scanner.useDelimiter(",");
        while(scanner.hasNext()){
            System.out.print(scanner.next()+"|");
        }
        scanner.close();
    }

}

For CSV File:

a,b,c d,e
1,2,3 4,5
X,Y,Z A,B

Output is:

a|b|c d|e
1|2|3 4|5
X|Y|Z A|B|
🌐
Coderanch
coderanch.com › t › 713986 › java › Reading-CSV-file-scanner
Reading a CSV file using scanner (Beginning Java forum at Coderanch)
August 4, 2019 - Just be aware that there are valid CSV files out there for which this will break. ... You need to close the Scanner when you're done with it. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
Discussions

Reading data from a CSV file
Read a whole line as a String, then .split(), and then parse (with type checking). More on reddit.com
🌐 r/learnjava
15
3
July 6, 2019
java - Reading a .CSV file using Scanner? - Stack Overflow
I have a .CSV file with a row of contents: Detroit 25 4 7 W Green Bay 7 7 4 L I create a new Scanner with the name of input Scanner input = new Scanner(file); //file here is the .... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
How do you read data from a .csv file in Java?
Use a Scanner with delimiter set to ",". Or use a library like OpenCSV or SuperCSV. Source: http://stackoverflow.com/questions/14274259/java-read-csv-with-scanner , http://stackoverflow.com/questions/123/java-lib-or-app-to-convert-csv-to-xml-file . Also, Stack Overflow will always be your friend. More on reddit.com
🌐 r/learnprogramming
2
1
March 4, 2014
How to read and print only specific rows of a CSV file?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
9
2
November 30, 2021
🌐
TechVidvan
techvidvan.com › tutorials › read-csv-file-in-java
How to Read CSV file in Java - TechVidvan
July 1, 2020 - Learn how to read CSV file in java in different ways-Using scanner class,Bufferedreader class,Java String.split(), OpenCSV API. Learn how to create CSV file
🌐
LabEx
labex.io › tutorials › java-reading-a-csv-file-117982
How to Read a CSV File in Java | LabEx
Reading CSV using Scanner Data read from CSV file: Row 0: name, age, city Row 1: John, 25, New York Row 2: Alice, 30, Los Angeles Row 3: Bob, 28, Chicago Row 4: Eve, 22, Boston · We import necessary Java classes for file operations, Scanner, and data structures.
🌐
Java Tips
javatips.net › blog › read-csv-file-using-java-scanner-class
Read CSV File Using Java Scanner Class - Javatips.net
May 27, 2018 - In below code I am using File as input. ... In the above code you can see, scanner class contains nextLine(), hasNext() methods which helps to iterate the data as per our required format. ... [User [name=Rockey, age=22, address=India], User [name=Bill, age=23, address=US], User [name=Sonia, age=23, address=Germany]] ... What are the Features Included in Java 11? Read This!
🌐
YouTube
youtube.com › watch
Reading a CSV with Scanner Example in Java - YouTube
In this video, I give an example of how to read a CSV file with the Scanner class in Java.See my video on exception handling here: https://youtu.be/42SSyoqI-...
Published   March 27, 2020
🌐
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 - We can use a separate Scanner to ... files because it is creating one scanner instance per line. We can use the delimiter comma to parse the CSV file....
Find elsewhere
🌐
Reddit
reddit.com › r/learnjava › reading data from a csv file
r/learnjava on Reddit: Reading data from a CSV file
July 6, 2019 -

I'm attempting to read data from a CSV file, then put each row into an object, then place the object inside an arraylists of objects. I seem to be getting an error on this line int age = fileReader.nextInt();

Can't seem to figure out what the issue is. Can anyone point me in the right direction?

Here is my full code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testfileio;

import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
/**
 *
 * @author gregf
 */
public class TestFIleIO {

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) 
            throws FileNotFoundException {
        Company jam = new Company();
        
        File csv = new File("C:\\Users\\gregf\\Documents\\NetBeansProjects\\TestFIleIO\\employees.csv");
        Scanner fileReader = new Scanner(csv);
        
        fileReader.useDelimiter(",|\n");
        //skips first row (column headers)
        fileReader.nextLine();
        
        while(fileReader.hasNext()) {
            String name = fileReader.next();
            int age = fileReader.nextInt();
            fileReader.nextLine();
            
            try {
                jam.setEmployees(new Employee(name, age));
            }
            catch(Exception ex) {
                System.out.println(ex);
            }
        }
        
        System.out.println(jam);
    }
    
}

A few notes:

  • Employee is an object with the name: String and age: int data fields

  • Company is an object that contains an ArrayList of Employee type and has a toString method to print all the emplyoee names and ages.

Edit: Here is my error:

Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:939)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at testfileio.TestFIleIO.main(TestFIleIO.java:50)
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:1328: The following error occurred while executing this line:
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:948: Java returned: 1
BUILD FAILED (total time: 0 seconds)
🌐
Baeldung
baeldung.com › home › java › java io › reading a csv file into an array
Reading a CSV File into an Array | Baeldung
May 9, 2025 - Furthermore, to parse the CSV file, we need to make the delimiter the same as in the CSV file: public static final String COMMA_DELIMITER = "\\|"; Let’s note that we need to escape special characters in a Java regular expression. With this regular expression, we can use a BufferedReader, Scanner, or the Files utility class to parse the sample CSV file into an ArrayList with elements as [“Kom, Mary”,Unbreakable], and [“Isapuari, Kapil”,Farishta].
🌐
LabEx
labex.io › tutorials › java-read-a-csv-file-117442
Read a CSV File in Java | LabEx
We used two methods to read the CSV file: using OpenCSV library and using Scanner class. The OpenCSV library provides a convenient way to read the CSV file but requires an external dependency.
🌐
Netjstech
netjstech.com › 2016 › 06 › reading-delimited-file-in-java-using-scanner.html
Reading Delimited File in Java Using Scanner | Tech Tutorials
Let's see an example where Scanner class is used to read a CSV file. ... Pride And Prejudice,Jane Austen,20.76 The Murder of Roger Ackroyd,Agatha Christie,25.67 Atlas Shrugged,Ayn Rand,34.56 Gone with the Wind,Margaret Mitchell,36.78 · And you want to read and parse the line so that you have Book name, author and price as separate strings. import java.io.File; import java.io.IOException; import java.util.Scanner; public class ScanDelimited { public static void main(String[] args) { // CSV file File file = new File("G:\\Temp.csv"); Scanner sc = null; try { sc = new Scanner(file); // Check if t
🌐
Attacomsian
attacomsian.com › blog › read-write-csv-files-core-java
How to read and write CSV files using core Java
September 24, 2022 - In this tutorial, we learned how to read and write CSV files using core Java without any 3rd-party library. You can use either the Scanner class or BufferedReader to read and parse a CSV file line by line.
🌐
Stack Overflow
stackoverflow.com › questions › 34100820 › reading-a-csv-file-using-scanner
java - Reading a .CSV file using Scanner? - Stack Overflow
May 22, 2017 - I have a .CSV file with a row of contents: Detroit 25 4 7 W Green Bay 7 7 4 L I create a new Scanner with the name of input Scanner input = new Scanner(file); //file here is the ....
🌐
Guvi
ftp.guvi.in › hub › java-examples-tutorial › reading-csv-file
Reading a CSV File in Java
We can see that no value is stored for the second row of the file(the comma has been omitted). We also don't require the quotation marks. ... We can also use the Scanner class of java.util package to read a CSV file.
🌐
CodeSpeedy
codespeedy.com › home › how to read csv file in java
How to read CSV file in Java - CodeSpeedy
July 2, 2021 - import java.io.*; import java.util.*; public class readCSVFile { public static void main(String[] args) throws FileNotFoundException{ // Read the file path Scanner sc = new Scanner(new File("C:\\Users\\Abinash\\Downloads\\a1-burtin.csv")); // Set the delimiter used in file.
🌐
Medium
medium.com › @zakariafarih142 › mastering-csv-parsing-in-java-comprehensive-methods-and-best-practices-a3b8d0514edf
Mastering CSV Parsing in Java: Comprehensive Methods and Best Practices | by Zakariafarih | Medium
November 25, 2024 - Simple CSV Files: For straightforward CSV files without embedded commas or quotes, basic file reading or the Scanner class suffices. Complex CSV Structures: When dealing with complex CSVs, external libraries like OpenCSV or Apache Commons CSV ...
🌐
Reddit
reddit.com › r/learnprogramming › how do you read data from a .csv file in java?
r/learnprogramming on Reddit: How do you read data from a .csv file in Java?
March 4, 2014 -

If I have an Excel file with columns of numerical values in and want to use these in a Java program how would I go about doing this?
In this case I have a few hundred rows of four-vectors (px, py, pz, E) and want to use the different values later on in the program (I can do this, it's just attempting to get the program to read them properly that's getting me stuck).

🌐
Attacomsian
attacomsian.com › blog › java-read-parse-csv-file
How to read and parse a CSV file in Java
September 24, 2022 - Another way of reading and parsing a CSV file in core Java is using the Scanner class. This class converts its input into tokens using a delimiter pattern.
🌐
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
Actually, there are a couple of ways to read or parse CSV files in Java e.g. you can use a third-party library like Apache commons CSV or you can use Scanner class, but in this example, we will use the traditional way of loading CSV files using BufferedReader.
🌐
Studytonight
studytonight.com › java-examples › how-to-read-a-csv-file-in-java
How to read a CSV file in Java - Studytonight
January 19, 2021 - Here, we used Scanner class and useDelimeter() method to specify the value separator. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) throws ...