1.Properties文件的创建
或者
结果
2.properties类与properties配置文件
我们平时可以通过java中的properties类创建对象对properties文件中的内容进行读写操作。
properties类继承自Hashtable类并实现了Map接口,也是使用一种键值对的形式来保存属性集,properties的键和值都是字符串类型。
3.Properties中的主要方法
3.1
public synchronized void load(InputStream inStream) throws IOException {
load0(new LineReader(inStream));
}
//load()将.properties属性文件对应的文件输入流,加载属性列表到Properties类对象。
使用方法:
File IO
可以使用File Stream的经典方式来读文件,然后解析。
//实例化对象
Properties properties = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream("src/main/resources/a.properties"));
properties.load(in);
这种实现方法上需要注意的就是传递文件路径时要传递相对路径(并且properties文件要在此类文件下的子目录中),如果properties文件和类文件分别在不同的目录中/路径中,那么传递的文件路径必须从两个文件相同的父目录开始。
例如:
需要传递:src/main/resources/a.properties
否则会报错,显示找不到指定文件
ClassLoader
采用classLoader的方式主要是通过它的grtResourceAsStream方法来实现加载properties文件。
Properties properties = new Properties();
// InputStream in = new BufferedInputStream(new FileInputStream("src/main/resources/a.properties"));
InputStream in = test.class.getClassLoader().getResourceAsStream("a.properties");
properties.load(in);
使用classLoader可以直接传递fileName。
但是在下面这种情况下就会出错;
例如:
3.2
public void store(OutputStream out, String comments)
throws IOException
{
store0(new BufferedWriter(new OutputStreamWriter(out, “8859_1”)),
comments,
true);
}
//这个方法将properties类对象的属性保存到输出流中。
Properties properties = new Properties();
//保存属性到b.properties文件
FileOutputStream outputStream = new FileOutputStream("b.properties",true);//true表示追加
properties.setProperty("iphone","11");
properties.setProperty("ipad","2018");
properties.store(outputStream,"test");
outputStream.close();
3.3 getProperty/setProperty
这两个方法分别是获取和设置属性信息。