在java 中的配置 文件一般都是properties文件后缀 的文本文件
文件内容格式 是 键=值 键唯一
文件内:等号左边的就是键 右边就是值
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username=root
password=root
一个键值占一行
操作properties文件 需要用到Properties这个对象 他继承Hashtable
Properties properties=new Properties();
常用方法;
用法 | 描述 |
---|---|
String getProperty(String key) | 用指定的键 搜索 对应的值 |
Object setProperty(String key,String values) | 调用Properties 中自带的HashTable 向里面添加键值 (自动调用put) |
void load(InputStream str) | 从输入流中读取文件内容 用于文件读取(键 值) |
void clear() | 清除Properties 类HashTable内所有的键值 |
Enumeration<T> keys() | 遍历所有key |
在使用前需要通过 load将文件的内容读取到 Properties对象里 然后就可以使用了
列:
创建一个test.properties 文件
a=b
c=d
e=f
创建一个test类
package cn.htsa.www.test;
import org.junit.Test;
import java.io.IOException;
import java.util.Properties;
public class test {
@Test
public void showriz() {
Properties properties=new Properties();
try {
properties.load(test.class.getClassLoader().getResourceAsStream("test.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String a = properties.getProperty("a");
System.out.println(a);
}
}
结果:b
遍历整个文件所有键,值
Properties pro=new Properties();
InputStream resource = Factory.class.getClassLoader().getResourceAsStream("benas.properties");
try {
pro.load(resource);
Enumeration<Object> keys = pro.keys();
while (keys.hasMoreElements()){
String key=(String)keys.nextElement();
String value=pro.getProperty(key);
}
} catch (Exception e) {
e.printStackTrace();
}
注意 如果 在junit 中获取不到 那么就在 main 里测试
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_45203607/article/details/120238413
内容来源于网络,如有侵权,请联系作者删除!