I am creating a Jar file to store common code for some of my other applications. Within one of the classes, I want to essentially load a csv file into an object, and allow applications that use the jar to access this object. I am using Java 8 and Apache Commons-csv.
Here is what I currently have:
public class MyServices {
public static final String CSV_SRC = "src/main/resources/MyCSV.csv";
private final List<MyCSVObj> allObjectsFromCSV;
public MyServices() {
this.allObjectsFromCSV = importMyCSV();
}
private List<MyCSVObj> importMyCSV() {
try {
Reader in = new FileReader(CSV_SRC);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
List<MyCSVObj> ret = new ArrayList<>();
for (CSVRecord record : records) {
... // Get all fields
// Add fields to list
}
return ret;
} catch (Exception e) {
LOGGER.error("Could not load csv", e);
}
return new ArrayList<>();
}
...
}
This works within eclipse and passes all tests. However, after compiling this as a jar and trying to use it within other projects, I get the specified exception "could not load csv" based on FileNotFoundException.
I have looked for the subject and a number of people have said to get the resource as a stream. Unfortunately, googling "Java import csv as stream", but this gives a bunch of manual csv parsing with Java 8 streams rather than using a CSV library.
I have also tried this with the same results (passes all tests in eclipse, but file does not load when imported to other projects):
FileInputStream is = new FileInputStream(CSV_SRC);
Reader in = new InputStreamReader(is);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
and this
Reader in = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("MyCSV.csv"));
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
Any suggestions on how to resolve the FileNotFoundException?