How to Read CSV file from a path in java using Jackson Library. And Parse Using CsvSchema, ObjectReader , CsvMapper. ANd then convert it to JSON object USing Jackson library. pLease HELP.
private void testCsvRead() throws Exception
{
String FILE_NAME = "G://Read folder/output.csv";
System.out.println("read csv");
ClassLoader classLoader = getClass().getClassLoader();
//-------------*****I am getting error here*****------------///
File file = new File(classLoader.getResource(FILE_NAME).getFile());
<-------------**********------------/
CsvSchema schema = CsvSchema.builder().addColumn("parentCategoryCode").addColumn("code").addColumn("name").addColumn("description").build();
CsvMapper mapper = new CsvMapper();
ObjectReader oReader = mapper.readerFor(OfferTemplateCategory.class).with(schema);
try (Reader reader = new FileReader(file)) {
MappingIterator mi = oReader.readValues(reader);
while (mi.hasNext())
{
System.out.println(mi.next());
}
}
}
I am getting error on this line(See above)
File file = new File(classLoader.getResource(FILE_NAME).getFile());
This is the error--->
java.lang.NullPointerException
at CSVtester.CsvTest.testCsvRead(CsvTest.java:39)
at CSVtester.CsvTest.main(CsvTest.java:26)
The likely issue here is that
classLoader.getResource(FILE_NAME)
returnsnull
.As you're using an absolute path for the file, you may want to simplify your code and simply use:
You can verify if your file exists by invoking
exists()
on theFile
object.Note
Here's the API for
Classloader#getResource
, and a likely explanation of why it'snull
in your case.