Search code examples
javaopencsv

How to construct openCSV CSVReader


Sorry for asking such a noob question. I've tried multiple things. All the examples I see online are what I tried in (1) and it isn't working.

String source= "C:\\temp\\data.csv"; CSVReader csvreader= new CSVReader(new FileReader(csv),","); 
  1. The above code gives the error "Constuctor CSVReader(FileReader, String) is not defined", but I've seen this used online. I think it is deprecated but can't I still use it? I checked the documentation and tried to use the constructor shown there in (2).

  2. String source = "C:\temp\data.csv";
    Reader reader = new FileReader(source); CSVReader csvreader= new CSVReader(reader);

Gives the error:

> Exception in thread "main" java.lang.NoClassDefFoundError:
> org/apache/commons/lang3/ObjectUtils  at
> com.opencsv.CSVParser.<init>(CSVParser.java:99)   at
> com.opencsv.CSVReader.<init>(CSVReader.java:99)   at
> csvpractice.main(csvpractice.java:54) Caused by:
> java.lang.ClassNotFoundException: org.apache.commons.lang3.ObjectUtils
>   at
> java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
>   at
> java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
>   at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
>   ... 3 more

Solution

    1. "Deprecated" means that you should not use it because it is liable to be removed in a later version. You are probably using such a later version, where it has been removed - so you REALLY cannot use it.
      The current API shows that it has been removed : http://opencsv.sourceforge.net/apidocs/com/opencsv/CSVReader.html

    2. String source = "C:\temp\data.csv";

    You have single-backslashes here, which means source will be "C:<tab>empdata.csv". Replace this by :

    String source = "C:\\temp\\data.csv";`
    
    1. You are missing the jar file that contains ObjectUtils. You can download it from : https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.0

    A better approach would be to use a build tool like Maven or Gradle, which will automatically import required dependencies.