Java | Dynamically read a file from AppServer Path. when file is outside WAR or EAR.

This post illustrates a way to read any file (say a properties file, XML File, XSLT File,  or image file ) as an InputStream object when the file needs to exist outside of an Application Context. Say you have an application accessible via a URL http://localhost:8080/MyApp, whose context is /MyApp.

Typically, there will be a WAR file responsible for this context /MyApp (say MyApp.war). Now if you want to access a file which is outside this context, In Glassfish app server there is a docroot folder where your domain is. This docroot folder serves as alternate root for documents.

  • Just create a folder, say, “data” under the docroot folder of your Glassfish domain.
  • Place your properties, image, or XML file there, say, myFile.xml.

In your web application, this will be accessible as URL

http://localhost:8080/data/myFile.xml    (you can check this direct “GET” URL in browser when web app is running)

You can read this URL as inputstream with the following code snippet:

String baseStaticFilePath = “”;
StringBuffer requestUrl = request.getRequestURL();
String requestUri = request.getRequestURI();
String ctxPath = request.getContextPath();
String baseAppUrl = requestUrl.substring(0, requestUrl.length() – requestUri.length() + ctxPath.length()) + “/”;

// this will give the base Application URL as  http://localhost:8080/MyApp/

Now all we need to do is to subsitute the MyApp with the “data” folder .

baseStaticFilePath = baseAppUrl.replaceAll(“MyApp“,”data“);

String outlierFileName = baseStaticFilePath + “myFile.xml”;

InputStream inputStream = new StreamSource(new URL(outlierFileName).openStream());

And we have the myFile.xml as InputStream object from within the web application.
The added benefit of obtaining this file as InputStream object is that any subsequent changes to this file are dynamically picked up (on the fly) on next call which would not be same as reading a file using getResourceAsStream() which is more of static in nature and may require AppServer restart.