版权声明:本文为博主原创文章,转载请说明出处。 https://blog.csdn.net/qq_42361748/article/details/88864483
Properties文件
xxx.properties 是java的一种配置文件,内容格式是键值对的方式存在,key = value ;
例如:age = 10 ;
在开发过程中将一些数据等配置在properties文件中,对项目的后期维护提供了便利。
Properties类的基础用法
Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。Properties类是线程安全的:多个线程可以共享单个Properties对象而无需进行外部同步。
读取Properties文件(根据key值获取value值)
public class PopUtil {
public static void main(String[] args) {
//properties文件放下src目录下
//InputStream ins = PopUtil.class.getResourceAsStream("/test.properties");
//properties文件放在类的同包下
InputStream in = PopUtil.class.getResourceAsStream("test.properties");
Properties p = new Properties();
try {
p.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(p.getProperty("name"));
System.out.println(p.getProperty("age"));
}
将properties文件中的数据存入到Map集合中
public Map<String, String> getMapByProperties(String name) {
Map<String, String> map = new HashMap<>();
Properties pop = new Properties();
InputStream ins = getClass().getResourceAsStream(name);
try {
pop.load(ins);
} catch (IOException e) {
e.printStackTrace();
}
Set<Entry<Object, Object>> set = pop.entrySet();
for (Entry<Object, Object> entry : set) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
return map;
}
将properties文件中的数据转化为XML文件
在项目下新建一个Test.xml的文件
package com.shang;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author shang
* @date 2019年3月28日
*/
public class PopUtil {
public static void main(String[] args) throws IOException {
Properties prop = new Properties();
InputStream in = PopUtil.class.getResourceAsStream("/test.properties");
prop.load(in);
FileOutputStream fos = new FileOutputStream("Test.xml");
prop.storeToXML(fos, "TEST");
fos.close();
}
}
运行结果:
将Test.xml中的数据读取出来
public class PopUtil {
public static void main(String[] args) throws IOException {
Properties prop = new Properties();
InputStream in = new FileInputStream("Test.xml");
prop.loadFromXML(in);
prop.list(System.out);
}
}
运行结果:
给properties文件写入数据
properties文件在项目下
public class PopUtil {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//加true,追加,不加true,则覆盖
OutputStream out =new FileOutputStream("test.properties",true);
properties.setProperty("color", "red");
properties.store(out, "AAA");
out.close();
}
}
加true运行结果:
不加true的运行结果“: