I have a problem with accessing an external file from my back bean. What I would like to do is to use ttf file in order to use the font through iText library. When I run my application via Netbeans 7.2 the code below works fine:
private static String fontPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("arialuni.ttf");
But as I deploy my ear file manually through Oracle Weblogic 11g console, ttf file is not found and I get NullPointerException.
I have tried several ways to get it work but no chance. If someone could help me, I would be greatly appriciated.
Regards
The ServletContext#getRealPath()
(and inherently thus also its JSF delegator ExternalContext#getRealPath()
) will return null
when the servletcontainer is configured to expand the deployed WAR in RAM memory space instead of in local disk file system space. "Heavy" servers are known to do that to improve performance. As there's no means of a physical local disk file system path which you could further utilize in File
or FileInputStream
, null
will be returned.
The getRealPath()
is absolutely the wrong tool for the purpose of obtaining the file's content. Never ever use getRealPath()
. You should be using ServletContext#getResourceAsStream()
(or its JSF delegator ExternalContext#getResourceAsStream()
) instead.
InputStream content = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/arialuni.ttf");
// ...
Note that you should absolutely not assign the InputStream
as a static variable for obvious reasons. If you really need to, read it into a byte[]
first so that you can safely close it.
The relative path you pass to FacesContext.getCurrentInstance().getExternalContext().getRealPath()
method, must be relative to context path of your FacesServlet.
lets say you have the "arialuni.ttf"
in your resources
folder in FacesServlet context path, then you should pass "/resources/arialuni.ttf"
to the getRealPath()
method like below:
FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/arialuni.ttf");
For details see this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With