Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaEE web - accessing files from /src/main/resources

I have a web application I'm writing and I need to access two files (xlsx) files. I'm not sure which web server I'll be using (Tomcat, Glassfish, or Other).

In my application I have a file located in:

/src/main/resources/Analysis_Template.xlsx

I'm trying to figure out how to access it from code.

The following code seemed to "sort of" work in WildFly but not in GlassFish

URI templateURI = this.getClass().getResource("/Analysis_template.xlsx").toURI();
File f = new File(templateURI.getPath());

Although this code did not crash f.canRead() returned false so I think it probably wasn't working. When I tried to run this under GlassFish things did not go well and it straight up crashed on the first line of code with a java.lang.NullPointerException

Any suggestions I'm sure its super obvious I'm just missing it.

--- Edits and Notes --

[I do end up with a WAR archive]

With WildFly the file is:

/usr/local/opt/wildfly-as/libexec/standalone/deployments/fleetForecast-1.0-SNAPSHOT.war/WEB-INF/classes/ANALYSIS_template.xlsx

Glassfish From what I can tell netbeans reports: In-place deployment at

~/devel/fleetforecast/target/fleetForecast-1.0-SNAPSHOT

And I find my file at:

~/devel/fleetforecast/target/fleetForecast-1.0-SNAPSHOT/WEB-INF/classes/ANALYSIS_template.xlsx

I have to read this file into a File object to pass to some code to create a set of XLSX files which will eventually be served up to the user.

like image 891
Jeef Avatar asked Aug 29 '26 19:08

Jeef


1 Answers

Try like this. When war files are packaged any files in /src/main/resources end at root level of your webapp. I think you should also prefer using getResourceAsStream over getResource because the later can only read files from file system.

BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Analysis_template.xlsx")));
// Now do something with br

I hope it helps.:)

like image 87
vkg Avatar answered Sep 01 '26 07:09

vkg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!