• Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I get a file at runtime from a Java class?  RSS feed

 
Paul Smiley
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a directory structure as follows:

webroot
-----WEB-INF
-----XSL


etc.

And I want to load an XSL file into memory from a JSF backing bean. This is simple from a JSP page and all, but I'm not sure how to do it from a Java class. Obviously, I don't want to hard code the path as this will be within a WAR file and is supposed to be portable.
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll need to use the FacesContext to get access to the ServletContext and then you can get to what you need just like you would from regular JSP/Servlets.
 
Paul Smiley
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much for the quick answer, Gregg.

Well, I used this:

ServletContext context = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext());

then this:

URL url = context.getResource("/XSL/filename.xsl");

And I get the error

java.lang.IllegalArgumentException: URI scheme is not "file"

- I'm trying to create a file object from this URL and cannot do it. Any ideas?
 
Rick Beaver
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try taking the / from the front of your URL
 
Paul Smiley
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I'll try that tomorrow.
 
Paul Smiley
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, that didn't work:

java.net.MalformedURLException: Path XSL/filename.xsl does not start with a "/" character
 
Paul Smiley
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the working solution:

ServletContext context = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext());

String xslFileName = context.getRealPath("/XSL/filename.xsl");

and create the file from there...


Thanks to everyone for their help!

 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!