How to get relative path of current directory in tomcat from linux environment using java

I would like to use the properties of my web application to read the file. I have deployed a war file to tomcat on a Windows environment and I can read the properties file from outside my web application using the following code.

//(Method 1.) String filePath = new java.io.File( ".").getCanonicalPath()+"/webapps/strsproperties/strs.properties"; // or //(Method 2.) String filePath = new File(System.getProperty("catalina.base"))+ "/webapps/strsproperties/strs.properties"; InputStream inputStream = null; inputStream = new FileInputStream(filePath); properties.load(inputStream); String application = properties.getProperty("applications"); 

In both cases, I can read filePath in windows.

The problem is that I cannot read filePath on Linux using the 1st method process (relative path).

Is there a way to read a file using the relative path in tomcat from Linux env ?.

+7
source share
3 answers

Your problem is that you do not know what the "current" directory is. If you are running Tomcat on Linux as a service, the current directory can be anything. Thus, new File(".") Will give you a random place in the file system.

Using the system property catalina.base much better, because Tomcat start script catalina.sh set this property. That way, this will work until you try to run the application on another server.

Good code would look like this:

 File catalinaBase = new File( System.getProperty( "catalina.base" ) ).getAbsoluteFile(); File propertyFile = new File( catalinaBase, "webapps/strsproperties/strs.properties" ); InputStream inputStream = new FileInputStream( propertyFile ); 

As you can see, the code does not mix lines and files. A file is a file, and a line is just text. Avoid using text for code.

Then I use getAbsoluteFile() to make sure I get the useful path in the exceptions.

Also make sure your code does not swallow exceptions. If you could see the error message in your code, you would immediately see what the code tried to find in the wrong place.

Finally, this approach is fragile. Your application crashes if the path changes when another web server is used and for many other cases.

Consider the webapp extension strsproperties to accept HTTP requests. Thus, you can configure the application to connect to strsproperties through the URL. This will work on any web server, you can even put it on another host.

+25
source

If your code runs inside the servlet, the easiest way is to use getServletContext().getRealPath("/strs.properties") to get the absolute path to the file.

+3
source

This is not a very reliable way. If you want your webapp to consume data from the "outside", then call System.getProperty to get the absolute path name that you specified with -D in the tomcat script configuration.

+1
source

Source: https://habr.com/ru/post/927475/


All Articles