Reputation: 1268
I have a java application running on a tomcat server. The application needs to read/write xml files to a directory.
I programmed it so that the files are written and read from the same directory using constant
public static final String DICTIONARY_PATH = getRelativePath() + "/res/dictionaries/";
which calls this method
public static String getRelativePath() {
return new File("").getAbsolutePath();
}
The constant is used in the methods readFromFile(String language)
and writeToFile(Dictionary dictionary)
When calling these methods from the main method running in IntelliJ (for testing purposes) it works beautifully and reads and writes files to the specified folder.
When these methods are called from the application when running on the tomcat server it can't find the files because it's looking in the tomcat/bin
folder of tomcat while the files are located in tomcat/webapps/application/WEB-INF/classes/dictionaries
How can I implement the method getRelativePath()
so that it works on both the tomcat server as locally in IntelliJ (by calling the main method)
Upvotes: 0
Views: 5366
Reputation: 430
I believe better to use context params using a listener class. Simply store that path in context or in servlet context for that matter. Or get relative path using servlet context.
Upvotes: 0
Reputation: 6814
You can use a properties file in Java to denote where tomcat/webapps/application/WEB-INF/classes/dictionaries
is. This will help you to setup tomcat directory as your "Actual target". using that property, you can always using relative paths e.g. ..\..\..\C:\myprojects\
to go to your java project for testing. Also, use them in combination with env variable. Note that you can always setup environment variables and access them using System.getenv(String name)
.
In case you don't know about properties file setup (very basic one) - http://crunchify.com/java-properties-file-how-to-read-config-properties-values-in-java/
The benefit of doing things through prop file is that your classes are intact. You change only properties file to point to values of whatever. Hardcoding file names and configs in OO design should be avoided if possible.
Upvotes: 1