如何读取file.properties

时间:2012-09-18 11:02:35

标签: java properties

我有一个项目组织了这个:

-LIBRERIA CLIENT/
   -SRC/
     -CONNECTION/
      CONNECTIONdB.JAVA
      CONFIG.PROPERTIES

CONNECETIONDB我有这段代码来阅读CONFIG.PROPERTIES文件:

public static void connect() throws RemoteException
{
        //read file config.properties:
        String dbHost="",dbUser="",dbPassword="";
        Properties prop=new Properties();
        try
        {
            //load il file:
            prop.load(new FileInputStream("src/Connectionconfig.properties"));
            //read the property of file
            dbHost=prop.getProperty("host");
            dbUser=prop.getProperty("user");
            dbPassword=prop.getProperty("password");
        }catch(FileNotFoundException fe){
            System.out.println("File not found");
        }catch(IOException ex){
            System.out.println("Error reading configuration file");
        }

但我有这个错误:

     FILE NOT FOUND 

有人能告诉我哪里出错了吗?

2 个答案:

答案 0 :(得分:1)

这很简单:您的代码在project_root的不同文件夹中执行。此外:src/Connectionconfig.properties不存在:如果您从project_root执行项目,它应该是SRC/CONNECTION/CONFIG.PROPERTIES
另请查看此内容以获取当前工作目录:Getting the Current Working Directory in Java

答案 1 :(得分:0)

您的代码阅读Connectionconfig.properties下的src文件,但根据您的项目结构,CONFIG.PROPERTIES下只有SRC/CONNECTION。 改为

  prop.load(new FileInputStream("SRC/CONNECTION/CONFIG.PROPERTIES"));

而不是

  prop.load(new FileInputStream("src/Connectionconfig.properties"));