JavaEE - WAR - Deployed :: How to read a file from resource directory
glassfish, jakarta-ee, java, maven, war
Solution
In the end it looks like this is the code that did the trick. I have NO idea why but apparently it worked and I'm not complaining.
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("/ANALYSIS_template.xlsx");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
I made a new project form scratch and this code worked. Thanks for the help guys!
Problem
I believe the "correct" way one is supposed to do this is `getResourceAsStream()` but it just doesn't seem to cut it. My situation: I have a web application in Java that will be eventually deployed to a few different web servers the possibilities are GlassFish, Tomcat, and WildFly. Currently I'm working on a mac with Netbeans and I have access to WildFly and GlassFish. The project is mavenized What I need to do is read and write two different Excel files. One serves as a "template" and one serves as the output file. The application previously ran standalone and I'm trying to wrap it into a JSF web site. I need to obtain an `FileInputStream` for my one of the methods and eventually create an output file which will be served back to the user via http. From what I gather the appropriate way to do this is supposed to be: XLSX File ``` /src/main/resources/ANALYSIS_template.xlsx ``` Location once compiled into WAR file :: WildFly ``` /usr/local/opt/wildfly-as/libexec/standalone/deployments/fleetForecast-1.0-SNAPSHOT.war/WEB-INF/classes/ANALYSIS_template.xlsx ``` Location once compiled into WAR file :: GlassFish ``` ~/devel/fleetforecast/target/fleetForecast-1.0-SNAPSHOT/WEB-INF/classes/ANALYSIS_template.xlsx ``` Java Code I think I've maybe managed to get an input stream to the file with the command: ``` InputStream is1 = getClass().getResourceAsStream("ANALYSIS_template.xlsx"); ``` I've also tried `("/ANALYSIS_template.xlsx")` by the way which behaves similarly. When I try to read from this input stream ``` try { is1.read(); } catch (IOException ex) { Logger.getLogger(FleetBean.class.getName()).log(Level.SEVERE, null, ex); } ``` I get a `java.lang.NullPointerException`. ``` Caused by: java.lang.NullPointerException at org.mitre.fleetforecast.bean.FleetBean.<init>(FleetBean.java:57) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at java.lang.Class.newInstance(Class.java:433) at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:186) ... 76 more ``` Any assistance offered or thought of would be greatly appreciated.