Properties简介

1 本身就是Map结构,是 HashTable的子类

2 其k,v必须是string类型

3 此map最大特色在于常和流搭档,因此常用于读写入 .properties  .xml

4 使用代码写法如下:

1 赋值

//创建对象
		Properties pro =new Properties();
		//存储
		pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
		//pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");
		pro.setProperty("user", "scott");
		pro.setProperty("pwd", "tiger");
		
		//获取
		String url =pro.getProperty("url","test");
		System.out.println(url);


2 写入数据到工程   ----> 默认自带盘符,不需指定根路径

public static void main(String[] args) throws FileNotFoundException, IOException {
		//创建对象
		Properties pro =new Properties();
		//存储
		pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
		pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");
		pro.setProperty("user", "scott");
		pro.setProperty("pwd", "tiger111");
		
		//存储到e:/others  绝对路径  盘符:
		//pro.store(new FileOutputStream(new File("e:/others/db.properties")), "db配置");  写出后文件为.properties
		//pro.storeToXML(new FileOutputStream(new File("e:/others/db.xml")), "db配置");    写出后文件为.xml
		
		//使用相对路径 当前的工程   默认相对路径是当前工程    都不要写根路径盘符   <--------------------------> 对比与在读取的时,使用相对路径下,需要用 /(表示bin) 来指定工程根路径盘符
    	pro.store(new FileOutputStream(new File("db.properties")), "db配置"); 
		//pro.store(new FileOutputStream(new File("src/db.properties")), "db配置");
		//pro.store(new FileOutputStream(new File("src/com/bjsxt/others/pro/db.properties")), "db配置");
	}



3 读取文件到内存   ----> 需指定根路径 /


	public static void main(String[] args) throws IOException {
		Properties pro =new Properties();
		//类相对路径的 /表示bin 翻译成字节码后的根目录,最后被翻译成字节码为: bin/包/类/class 而bin则为/表示
		pro.load(Demo04.class.getResourceAsStream("/com/bjsxt/others/pro/db.properties"));   // 倾向于用这种方式 
		// 或者用类加载器方式获取相对路径
		//pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/bjsxt/others/pro/db.properties"));
		System.out.println(pro.getProperty("user", "bjsxt"));
	}

猜你喜欢

转载自chengjianxiaoxue.iteye.com/blog/2180884