Ton*_*ony 0 java properties file
我想从名为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();
}
Run Code Online (Sandbox Code Playgroud)
如果将属性文件移动到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();
}
Run Code Online (Sandbox Code Playgroud)
这里YourClass是什么类的代码在不在。
Maven将已编译类的类文件和所有资源放置src/main/resources在WEB-INF/classes只有您的应用程序可以访问它们的地方。
如果将文件放入src/main/resources/someFolder,则需要从
prop.load(YourClass.class.getResourceAsStream("/someFolder/jdbcProperties"));
Run Code Online (Sandbox Code Playgroud)
您提供给上述方法的路径是相对于您所在类的包的,除非您指定前导正斜杠,否则,它将相对于类路径的根(即,classes文件夹)。
| 归档时间: |
|
| 查看次数: |
3803 次 |
| 最近记录: |