简体   繁体   中英

How to read a file from Eclipse's path on a Dynamic Web Project?

I'm using Eclipse Kepler with Tomcat 7 (localhost) and my project is a Dynamic Web Project .

I have a class that needs to load some properties files:

File dir = null;
try {
    dir = new File(globalPropertiesFolder);
} catch (NullPointerException e) {
    log.error("Could not open the specified properties folder: "
            + globalPropertiesFolder, e);
}

if (dir == null) {
    log.error("Could not open the specified properties folder: "
            + globalPropertiesFolder);
    return;
}

FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        boolean res = false; 
        res = !name.endsWith("dynamic.properties");
        if (!name.endsWith(".properties"))
            res = false; 
        return res;
    }
};
String[] children = dir.list(filter);

Where globalPropertiesFolder is a string that is equal to "config/properties".

I have a main in this class for testing some methods, when I run it as Java Application the properties are found, and the children variable is filled with the content of that folder, but, when I ran it the whole project on server (Tomcat) it can't find the properties.

I have noticed that the file has a different absolute path ( dir.getAbsolutePath() ) when I ran it as Java Application to when I ran it on server so the final question is: how can I list the files on a folder on a dynamic web project using Eclipse and Tomcat as a server? If I can at least, list all of them, and then I can load all the files I need.

A reliable way to locate files both in standalone applications and in web applications, is via the classpath, like so:

    ClassLoader cl = this.getClass().getClassLoader();
    InputStream is = cl.getResourceAsStream("resources/foo.properties");

The specified file name will be searched via the class loader, ie relative to any of your application's class path entries. In this example you could create resources/foo.properties inside your src folder, for instance, and it would be found both in standalone and in web mode. Unfortunately this requires you to know the relative file names in advance, ie you can't list them prior to loading.

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