我想从名为 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/