一.普通java项目
1.目录结构
注意:db.properties放在src目录下

2.app代码示例
package com.test;
import java.util.resourcebundle;
public class app {
public static void main(string[] args) {
//放src目录下的db.properties
resourcebundle resource = resourcebundle.getbundle("db");
string key = resource.getstring("driver");
system.out.println(key);
}
}
3.db.properties文件示例
driver=com.mysql.cj.jdbc.driver
4.结果示例

5.db.properties放指定目录下
- 目录结构

//app代码示例
package com.test;
import java.util.resourcebundle;
public class app {
public static void main(string[] args) {
//包名+文件名
resourcebundle resource = resourcebundle.getbundle("com.test.db");
string key = resource.getstring("driver");
system.out.println(key);
}
}
二.maven项目
- maven项目properties需要放在resources文件夹目录下
- 直接放包名中是无效的
1.目录结构

2.app代码示例
package com.xiaoi;
import java.util.resourcebundle;
public class app {
public static void main( string[] args ) {
resourcebundle resource = resourcebundle.getbundle("db");
string key = resource.getstring("driver");
system.out.println("key"+key);
}
}3.db.properties示例
driver=com.mysql.cj.jdbc.driver
4.如果放包里会出现异常
exception in thread "main" java.util.missingresourceexception: can't find bundle for base name db, locale zh_cn
at java.util.resourcebundle.throwmissingresourceexception(resourcebundle.java:1581)
at java.util.resourcebundle.getbundleimpl(resourcebundle.java:1396)
at java.util.resourcebundle.getbundle(resourcebundle.java:782)
at com.xiaoi.app.main(app.java:10)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论