简要介绍
近期在工作中遇到使用Properties类进行IO读写配置文件的情况,于是乎对此类有了兴趣,在网上一通学习后,来这里总结下。我们先来看下部分源码
public class Properties extends Hashtable<Object,Object> {
/**
* use serialVersionUID from JDK 1.1.X for interoperability
*/
@java.io.Serial
private static final long serialVersionUID = 4112578634029874840L;
private static final Unsafe UNSAFE = Unsafe.getUnsafe();
可以看到这个类继承自HashTable<k,v>,当然也实现了Map<k,v>接口,所以他可以当做一个Map来使用,而且还是一个双列集合,其中的k,v都是字符串类型。我们来举例演示下Properties的集合属性
@Test
void contextLoads() {
Properties prop = new Properties();
prop.put("name","Superman");
prop.put("age",18);
System.out.println(prop.toString());
prop.clear();
System.out.println(prop.toString());
}
我们看下输出的结果
可以看到集合中是以key-value的形式存放的。那平时我们使用最多的Properties的场景肯定就是.properties的配置文件了,我们来看下这个类是否可以读取到配置文件。
@Test
void contextLoads() {
File file = new File("src/main/resources/demo.properties");
File file1 = new File("src/main/resources/demo1.yml");
Properties properties = new Properties();
try(FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"))
{
properties.load(inputStreamReader);//读取输入字符流
System.out.println(properties);
System.out.println(properties.getProperty("name"));
}catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
两个配置文件分别如下:
我们来看下分别读取两个配置文件的结果
我们可以看到load这个方法参数可以传输入字符流Reader reader,同样也可以传入输入字节流InputStream inputStream。都是可以读取的。再来看下这个类另一个方法replace方法
File file = new File("src/main/resources/demo.properties");
File file1 = new File("src/main/resources/demo1.yml");
Properties properties = new Properties();
try(FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"))
{
properties.load(inputStreamReader);
System.out.println(properties);
System.out.println(properties.getProperty("name"));
properties.replace("name","SpiderMan","yang");
System.out.println(properties);
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我们来看下结果:
可以看到Properties这个集合中的属性已经发生了变化,但是如果我们想要修改配置文件,也就不仅读,还要进行硬盘的写,是否可以实现呢?我们加上下面这段代码:
try {
final FileOutputStream fileOutputStream = new FileOutputStream(file);
properties.store(fileOutputStream,"change");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
看下结果
输出没有变化,看下resources中的源文件
可以看到已经修改了,而且还有修改时的备注也就是comment。Properties类其实还有很多其他应用,基本上都是关于配置文件。比如我们可以通过System的getProperties方法去获取当前JVM的所有参数信息,并打印输出到控制台中。相关实例代码如下:
@SpringBootTest
public class JVMPropertiesTest {
@Test
void testDemo(){
Properties properties = System.getProperties();
properties.list(System.out);
}
}
相关展示信息:
还有很多参数不截全图了。我们可以用流输出到文档中方便查看。
以上就是关于这个类目前所学到的东西,分享给大家。