版权声明:LemonSnm https://blog.csdn.net/LemonSnm/article/details/89913630
Properties: (java.util.Properties)
主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中有很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量配置。
主要的方法:
getProperty(String key):用指定的键在此属性列表中搜索属性。也就是通过参数key,得到key所对应的value。
load(InputStream inStream):从输入流中读取属性列表(键和元素对)。通过指定的文件(config.properties)进行装载来获取该文件中的所有键-值对。以供getproperty(String key)来搜索。
setPrperty(String key,String value):调用Hashtable的方法put。它通过调用基类的put方法来设置键-值对。
store(OutputStream out,String comments):以适合load方法加载到properties表中的格式,将此properties表中的属性列表(键-元素对),写入输出流。与load方法相反,该方法将键-值对写入到指定的文件中去
clear:清除所有装载的键-值对。该方法在基类中提供
Properties作用:
* 1、可以用来做配置文件
* 2、javaweb、javaee开发中通常会用到
代码示例:
package com.lemon;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
* Properties:
* 1、可以用来做配置文件
* javaweb、javaee开发中通常会用到
*
* ResourceBundle:可读
* Properties: 可读可写
*
* @author lemonSun
* 2019年5月7日上午8:05:01
*/
public class PropertiesDemo {
private static String version = "";
private static String username = "";
private static String password = "";
public static void main(String[] args) {
//writeConfig("4","张三","111111");
readConfig();
System.out.println(version);
System.out.println(username);
System.out.println(password);
}
//静态代码块,只会执行一次
static {
// readConfig();
}
/**
* 对配置文件的读取
*/
private static void readConfig() {
//文件操作
Properties p = new Properties();
try {
//通过当前线程的类加载器对象,来加载指定包下的配置文件
//InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/resources/config.properties");
//config.properties 工程目录下
InputStream ins = new FileInputStream("config.properties");
p.load(ins);
version = p.getProperty("app.version");
username = p.getProperty("db.username");
password = p.getProperty("db.password");
ins.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 对属性文件的写入
* @param version
* @param username
* @param password
*/
private static void writeConfig(String version,String username,String password) {
Properties p = new Properties();
p.put("app.version",version);
p.put("db.username",username);
p.put("db.password",password);
try {
OutputStream out = new FileOutputStream("config.properties");
//写文件
p.store(out, "update config"); //写文件, "update config"日志信息
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}