java - Eclipse 不会读取配置文件

标签 java inputstream properties-file

我有一个 Eclipse 网络项目。我在根目录中有一个名为 deploy.properties 的文件,该文件似乎无法读取。我有一种感觉,我可能需要将文件添加到“构建路径”(如 jar),但这只是一个猜测,当我尝试这样做时,没有将文件添加到构建路径的选项,因此让我觉得我错了。

第 89 行就是这个 props.load(stream);

我的堆栈跟踪看起来像这样:

java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:365)
at java.util.Properties.load(Properties.java:293)
at sempedia.dao.Dao.getConfigFile(Dao.java:89)
at sempedia.dao.Dao.<clinit>(Dao.java:17) 89 

类看起来像这样:

public class Dao {
private static final String configFileLocation = "/deploy.properties";

private static final Properties configFile = getConfigFile(configFileLocation);

private static final String host = configFile.getProperty("mysql.host");
private static final String port = configFile.getProperty("mysql.port");
private static final String db   = configFile.getProperty("mysql.db");
private static final String user = configFile.getProperty("mysql.user");
private static final String pwd  = configFile.getProperty("mysql.pwd");

public static String getHost() { return host; }

public static String getPort() { return port; }

public static String getDb() { return db; }

public static String getUser() { return user; }

public static String getPwd() { return pwd; }


public static Connection getCon() {
    Connection con = null;
    try {
        String url = "jdbc:mysql://" + host + ":" + port + "/" + db;
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = DriverManager.getConnection(url, user, pwd);

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return con;
}

private static Properties getConfigFile(String fileName) {
    Properties props = new Properties();
    try {
        InputStream stream = Dao.class.getResourceAsStream(fileName);
        props.load(stream);
    } catch (IOException e) {
        System.err.println("Error opening configuration file");
        System.exit(1);
    }

    return props;
}
}

最佳答案

请记住,当您在 eclipse 项目中读取文件时,默认位置在您的源目录中(如果这是一个 Web 应用程序,稍后会转换为您的类目录)。所以我的建议是尝试将文件从项目根目录移动到“src”目录并重试。

关于java - Eclipse 不会读取配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6014432/

相关文章:

java - 使用 Maven 配置文件加载正确的属性文件时获取 NPE

java - 复制 InputStream,如果大小超过限制则中止操作

java - 需要知道每个字段是否已更改,我应该如何在 Hibernate 中对其进行建模

java - 用于读取临时参数的PreparedStatement

java - 无法使用 Tycho 和 Java 9 构建 Eclipse RCP 项目

java - 无法从非空InputStream读取内容

java - InputStream.close() 有什么作用吗?

java - 按字母顺序对 .properties 文件中的键进行排序,同时忽略大小写

yaml - 将 YAML 文件转换为 vault kv put 的属性文件

java - 如何使用 JAX-RS 转发请求?