Csvs on resources folder not found from bootjar

Hello,
My application runs properly in studio but when i build the BootJAR it cannot find the csvs in my main resource folder

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.company.app.beans.factory.util.WorkerFactoryHelper]: Constructor threw exception; nested exception is java.lang.RuntimeException: java.io.FileNotFoundException: C:\Users\compuser\OneDrive - COMPANY\Desktop\app\app\jdk\bin\src\main\resources\csv-files\maleNames.csv (The system cannot find the path specified)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224) ~[spring-beans-5.3.22.jar!/:5.3.22]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.3.22.jar!/:5.3.22]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1326) ~[spring-beans-5.3.22.jar!/:5.3.22]
        ... 81 common frames omitted
Caused by: java.lang.RuntimeException: java.io.FileNotFoundException: C:\Users\compuser\OneDrive - COMPANY\Desktop\app\app\jdk\bin\src\main\resources\csv-files\maleNames.csv (The system cannot find the path specified)

the way i load the CSV is like this

 public static String[] csvReader(String csvFileName) {
        try {
            String folderPath = "\\src\\main\\resources\\csv-files\\";
            String csvPath = System.getProperty("user.dir") + folderPath + csvFileName + ".csv";
            CSVReader csvReader = new CSVReader(new FileReader(csvPath));
            List<String> elements = csvReader.readAll().stream()
                    .map(a -> a[0]).collect(Collectors.toList());
            return elements.toArray(new String[0]);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

When your application is assembled, your file is inside the JAR, so it cannot be read by FileReader. You should read from the classpath.

Everything from src/main/resources is copied to the classpath root, so your file must be in the /csv-files/ path. Use one of the methods described at Access a File from the Classpath using Spring. It will work both when you run the application in Studio and after deployment.

1 Like