为什么我的系统找不到我的属性文件?

Why can't my system find my properties file?

我在 src/config 下有一个名为 admin.properties 的属性文件,每当我 运行 程序时,它都会给我这个错误:

java.io.FileNotFoundException: admin.properties (The system cannot find the file specified)

这是我的代码:

package com.in.props;

public class Props {
    public static void main(String[] args) {
        String filePath = "config/admin.properties";
        Properties adminProps = new Properties();
        adminProps.load(new FileInputStream(filePath));
        String userName = adminProps.getProperty("userName").trim();
        String password = adminProps.getProperty("password").trim();
    }
}

这是属性文件,admin.properties:

userName=test
password=test

我的Propsclass(在com.in.props)和admin.properties(在config)在不同的目录下。

Project_Root
-src
 -config
   -admin.properties
 -com
   -in
     -props
       -Props.java

我没有使用 eclipse,我想通过命令提示符执行它。

使用 ClassLoader 加载文件要容易得多。使用 getClass().getResourceAsStream() 获取类路径中的文件:

InputStream is = Props.class.getResourceAsStream("/src/config/admin.properties");
if(is != null) {
    Properties adminProps = new Properties();
    adminProps.load(is);

请注意,前导斜线非常重要。