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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With