简体   繁体   中英

Read a file from Tomcat webapps on different Tomcats

Consider the following: I got a csv-file. This file is stored in the tomcat wepapps directory. The path to this directory is dependent of the computer used. There are users that use different locations for their Tomcats and use different names. I want to achieve the following.

Via Spring i did the following: I got an action which imports some data from the csv to the database.

<bean id="setCsvPathAction" class="custom.action.importcsv.SetCsvPathAction">
   <property name="csvPath" value="C:/temp/test.csv"/>
</bean>

This works fine for me. To make this path more configurable for others i got a system.properties file. With this file you can easily overrite properties:

setCsvPathAction.csvPath=#{tomcat_home}/webapps/test.csv

That is what i want. I want the path to be on the Tomcat webapps directory. The above doesn't work. Do you have any hint how to achieve this?

Most people who use tomcat would have set CATALINA_HOME environment variable. You can query this environment variable and retrieve value.

String tomcat_home = System.getenv("CATALINA_HOME");
if(tomcat_home){
    setCsvPathAction.csvPath=tomcat_home+"/webapps/test.csv"
}

Note: There's no guarantee that this environment variable is set on every system using tomcat

More on getenv() - http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getenv%28%29

If it is going to be in the web apps folder you could also just use the class loader to get the local path so you do not have to configure anything.

someObject.getClass().getClassLoader().getResourceAsStream("path/refferenced/to/app/root/");

The solution for the .properties file was: ${catalina.home} Next i need a FileInputStream independent of the system environment. I tried the following:

public class environmentTest {

    public static void main(final String[] args) {
        System.out.println(System.getenv("CATALINA_BASE"));
    }

}

null gets printed on the console.

The class Person contains the name of the jpg file. This file is located at the webapps folder. I want the path to be independent of the computer used. I tried the following:

File file = new File(System.getenv("CATALINA_HOME") + "/webapps/" + person.getPhoto());
FileInputStream fileInputStream = new FileInputStream(file);

Sadly this doesn't work because, as unekwu said, this environment variable is not set on all systems. Do you have any idea what i can do in this situation?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM