Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从Eclipse读取文件';动态Web项目上的路径?_Java_Eclipse_File_Tomcat - Fatal编程技术网

Java 如何从Eclipse读取文件';动态Web项目上的路径?

Java 如何从Eclipse读取文件';动态Web项目上的路径?,java,eclipse,file,tomcat,Java,Eclipse,File,Tomcat,我将EclipseKepler与Tomcat7(localhost)一起使用,我的项目是一个动态Web项目 我有一个类需要加载一些属性文件: File dir = null; try { dir = new File(globalPropertiesFolder); } catch (NullPointerException e) { log.error("Could not open the specified properties folder: "

我将EclipseKepler与Tomcat7(localhost)一起使用,我的项目是一个动态Web项目

我有一个类需要加载一些属性文件:

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);
其中globalPropertiesFolder是一个等于“config/properties”的字符串

这个类中有一个main用于测试一些方法,当我作为Java应用程序运行它时,会找到属性,并且children变量会填充该文件夹的内容,但是当我在服务器上运行整个项目(Tomcat)时,它找不到属性


我注意到,当我作为Java应用程序运行该文件时,它的绝对路径(
dir.getAbsolutePath()
)与在服务器上运行该文件时不同,所以最后一个问题是:如何在使用Eclipse和Tomcat作为服务器的动态web项目中列出文件夹中的文件?如果我至少可以列出所有文件,然后我可以加载所有需要的文件。

在独立应用程序和web应用程序中查找文件的可靠方法是通过类路径,如下所示:

    ClassLoader cl = this.getClass().getClassLoader();
    InputStream is = cl.getResourceAsStream("resources/foo.properties");
指定的文件名将通过类加载器进行搜索,即相对于应用程序的任何类路径条目进行搜索。例如,在本例中,您可以在
src
文件夹中创建
resources/foo.properties
,它可以在独立模式和web模式下找到。 不幸的是,这要求您提前知道相关文件名,即在加载之前不能列出它们