Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.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 从动态Web项目中的类打开属性文件_Java_Eclipse_Jsp_Properties File - Fatal编程技术网

Java 从动态Web项目中的类打开属性文件

Java 从动态Web项目中的类打开属性文件,java,eclipse,jsp,properties-file,Java,Eclipse,Jsp,Properties File,我正在为EE开发者使用Eclipse 我需要从类的方法(DBQuery.java)访问属性文件(db.properties)。 该类位于src文件夹内的包中。 对于属性文件,我尝试了几乎所有我能在网上找到的东西来让它工作,但看起来我做不到。 属性文件位于WebContent文件夹中,我将添加尝试加载此文件的代码: public class DBQuery { public static String create_DB_string(){ //the db conne

我正在为EE开发者使用Eclipse

我需要从类的方法(DBQuery.java)访问属性文件(db.properties)。 该类位于src文件夹内的包中。 对于属性文件,我尝试了几乎所有我能在网上找到的东西来让它工作,但看起来我做不到。 属性文件位于WebContent文件夹中,我将添加尝试加载此文件的代码:

public class DBQuery {

    public static String create_DB_string(){

        //the db connection string
        String connString = "";

        try{
            Properties props = new Properties();
            FileInputStream fis = new FileInputStream("db.properties");

            props.load(fis);
            fis.close();

                /* creating connString using props.getProperty("String"); */

         }
       catch (Exception e) {
            System.out.println(e.getClass());
        }       
        return connString;
    } 
}

因此,我的问题是,将属性文件放在何处,以及加载它的正确方法是什么?

您可以将此属性文件放在java包(例如com/test)中,并使用以下方法:

getClass().getResourceAsStream(“com/test/myfile.property”)


希望有帮助。

这是读取/加载它的正确方法;不是关闭I/O资源的正确方法。您必须确保
.properties
文件位于类路径中。您正在使用Maven吗?如果您的文件db.properties在包中,那么您需要提到这一点。@uıuɥuɔuɔɯ好的,谢谢您的回复。我关闭了FileInputStream,在类路径中添加了包含db.properties的文件夹,但仍然无法工作。顺便说一句,我没有使用maven,这是什么?如果你想使用它,建议你更容易,因为每个人都知道目录结构。答案是一样的:
.properties
必须在类路径中。请尝试单独复制文件并使用它,直到得到结果,然后将其放入目录中并更改代码(因为在这种情况下,还需要包括文件所在的目录)。谢谢,dude,我实际上使用“InputStream fis=DBQuery.class.getResourceAsStream(“db.properties”);”使其工作正常。再次感谢:)