How to Read CSV file in java using Jackson Library

2019-08-20 01:46发布

问题:

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)

回答1:

The likely issue here is that classLoader.getResource(FILE_NAME) returns null.

As you're using an absolute path for the file, you may want to simplify your code and simply use:

File file = new File("G://Read folder/output.csv");

You can verify if your file exists by invoking exists() on the File object.

Note

Here's the API for Classloader#getResource, and a likely explanation of why it's null in your case.