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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32343784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:03:37  来源:igfitidea点击:

Why can't my system find my properties file?

javajava-iofilenotfoundexception

提问by haja

I have a properties file called admin.propertiesunder src/configand whenever I run the program it gives me this error:

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

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

java.io.FileNotFoundException: admin.properties (系统找不到指定的文件)

Here is my code:

这是我的代码:

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();
    }
}

Here's the properties file, admin.properties:

这是属性文件 admin.properties:

userName=test
password=test

My Propsclass (in com.in.props) and the admin.properties(in config) are under different directories.

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

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

I am not using eclipse and I want to execute this via command prompt.

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

采纳答案by durron597

It's much easier to load files using the ClassLoader. Use getClass().getResourceAsStream()to get files that are on your classpath:

使用ClassLoader.使用getClass().getResourceAsStream()来获取对你的类路径中的文件:

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

Note that the leading slash is very important.

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