Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Pointer Exception in Reading file from resources java

I'm trying to read a .csv file from my resource folder in my maven project. I've done it before like this:

BufferedReader reader = new BufferedReader(
new InputStreamReader(this.getClass().getResource("info.csv").openStream()));

CSVParser csvParser = new CSVParser(reader,
CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());

and it worked. and now in another project, I'm trying read my file from resources and I get NullPointerException.

The only thing that is different between these 2 projects is my packages.

This is for the one that works:

and This is the one that doesn't work:

What am I doing wrong?

like image 243
Shaghayegh Tavakoli Avatar asked Jun 06 '18 09:06

Shaghayegh Tavakoli


People also ask

How do I fix NullPointerException in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Can NullPointerException be caught in Java?

The java. lang. NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

What causes NullPointerException in Java?

Some of the common reasons for NullPointerException in java programs are: Invoking a method on an object instance but at runtime the object is null. Accessing variables of an object instance that is null at runtime. Throwing null in the program.

Can NullPointerException be caught?

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.


1 Answers

Add a slash before the filename:

new InputStreamReader(this.getClass().getResource("/info.csv").openStream()));

without slash it looks in the same directory structure than your class is located

like image 98
Jens Avatar answered Sep 20 '22 19:09

Jens