JAVA-I/O流-Properties类

JAVA-I/O流-Properties类


Properties类是用于读取java配置文件的类,当代码设计完成后,有些数据需要改变,但是我们不想去改变代码本身,于是配置文件就产生了,通过Properties类我们可以在只更改配置文件的情况下让程序中的一些数据进行改变,从而通过不更改代码的方式来改变程序中的参数。

  • JavaAPI:Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

方法

getProperty(String key)	// 获取键所对应的值
setProperty(String key, String value) // 添加键值对
load(InputStream inStream) // 从输入字节流中获取属性列表
load(Reader reader) // 从输入字符流中获取属性列表,不在Latin中的字符需要用Unicode转义符的肩和元素中表示
store(OutputStream out, String comments) // 使用输出流写入文件
clear()  // 清除此哈希表,使其不包含任何键
}

使用Properties类存储键值对并写入本地文件

// 目的地 & Properties对象
FileOutputStream fos = new FileOutputStream("D:/io1227/baa/pro.txt");
Properties pro = new Properties();
// 往Properties对象中存储值
pro.setProperty("user", "root");
pro.setProperty("password", "root");
pro.setProperty("Driver", "com.mysql.jdbc.Driver");
pro.setProperty("url", "jdbc:mysql://localhost:3306/demo1227?characterEncoding=utf8");
// 向节点流输入内容
pro.store(fos, "");

使用Properties类来创建获取Connection对象的方法

public static Connection getconn(){
		
	Connection conn = null;
	
	try {
	// 数据源 & 新建Properties类				
	FileReader fr = new FileReader("src/com/oracle/demo02/db.properties");
	Properties pro = new Properties();
	pro.load(fr);
	
	Class.forName(pro.getProperty("driver"));
	String url = pro.getProperty("url");
	String password = pro.getProperty("password");
	String user = pro.getProperty("user");
		conn = DriverManager.getConnection(url, user, password);
	} catch (SQLException | ClassNotFoundException | IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		return conn;
	}		
}

猜你喜欢

转载自www.cnblogs.com/torain/p/12770495.html