java - 如何读取属性文件?

标签 java file properties

我想从名为 jdbc.properties 的属性文件中读取一行。它位于src\main\webapp\WEB-INF\db\jdbc.properties。我应该使用什么路径? 这是我的方法:

Properties prop = new Properties();

        try {
            // load a properties file
            prop.load(new FileInputStream("jdbc.properties"));

            System.out.println(prop.getProperty("password"));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

最佳答案

如果您将属性文件移动到src/main/resources,假设您的项目由maven管理,那么您可以通过执行以下操作来检索它

Properties prop = new Properties();

try {
    // load a properties file
    prop.load(YourClass.class.getResourceAsStream("/jdbc.properties")); // note the leading /

    System.out.println(prop.getProperty("password"));

} catch (IOException ex) {
    ex.printStackTrace();
}

其中 YourClass 是此代码所在的类。

Maven 将已编译类的类文件和 src/main/resources 中的所有资源放置在 WEB-INF/classes 中,只有您的应用程序可以访问它们。

如果您将文件放在 src/main/resources/someFolder 中,则需要从

访问它
prop.load(YourClass.class.getResourceAsStream("/someFolder/jdbcProperties"));

您提供给上述方法的路径是相对于您所在类的包的,除非您指定前导正斜杠,在这种情况下它将相对于类路径的根,即 文件夹。

关于java - 如何读取属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18239902/

相关文章:

C#:用属性代替公共(public)变量不是很麻烦吗?

java - Tomcat 8.0.32 - 更新了网络应用程序未使用的共享库

java - 为什么 i+=l 会编译,其中 i 是 int 而 l 是 long?

java - 在 jdk 6 与 jdk 8 中创建临时目录

c# - 如何只获取可以复制的文件?

Java 读取文件到字节数组 - 最有效的实现

c# - 检测类属性是否为引用类型

properties - 未设置外部属性时,Gradle 三元/elvis 运算符未设置 'else' 值

java - 文字谜题 - 如何解决它超出路径的问题?

java - 将图像转换为文本 - Java