I have two classes in a Maven project, which contain the same code (except for their name). The code shall later create a new class with Javassist based on a csv-file.
The first one CsvParser
is placed in the src/main/java/csvParser
package. The second one TestCsvParser
is placed in the src/test/java/csvParser
package. In both packages the same file assistant.csv
is placed.
When I run the one from the main
directory (CsvParser
) I get a java.lang.NullPointerException
but when I run TestCsvParser
, placed in the test
directory the same code works fine.
Why is it like that? (Or do I just not see something? ;) )
CsvParser
:
package csvParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CsvParser {
public static void main(String[] args) throws IOException
{
createClass("/assistant.csv");
}
/**
* Create a class from a csv-file.
*/
private static void createClass(String input) throws IOException {
try(BufferedReader stream = new BufferedReader(new InputStreamReader(
CsvParser.class.getResourceAsStream(input))))
{
// Create class based on csv-file.
}
}
}
TestCsvParser
:
package csvParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestCsvParser {
public static void main(String[] args) throws IOException
{
createClass("/assistant.csv");
}
/**
* Create a class from a csv-file.
*/
private static void createClass(String input) throws IOException {
try(BufferedReader stream = new BufferedReader(new InputStreamReader(
TestCsvParser.class.getResourceAsStream(input))))
{
// Create class based on csv-file.
}
}
}
The exception
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at csvParser.CsvParser.createClass(CsvParser.java:19)
at csvParser.CsvParser.main(CsvParser.java:11)
I believe this question is not a duplicate of a question like What is a NullPointerException
because:
The NullPointerException
occurs based on the location of the class and the resource referred to. So it's more about directory structures and Mavens target
directory.
Thanks for your time!