package com.mipo.collection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
* properties类是Hashtable的子类
* Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
* 作用:读写资源配置文件。
* @author Administrator
*
*/
public class TestProperties {
public static void main(String[] args) {
test1();
test2();
test3();
test4();
}
//创建Properties对象,进行存储和读取操作
public static void test1 () {
//创建对象
Properties pro = new Properties();
//存储
pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");
pro.setProperty("user", "sa");
pro.setProperty("pwd", "sasa");
//获取
String url = pro.getProperty("url","test");//如果未找到属性,则此方法返回默认值变量。
System.out.println(url);
}
//使用Properties输出到文件,即资源配置文件。可以动态的更改数据库,而不需要更改代码。
public static void test2 () {
//创建对象
Properties pro = new Properties();
//存储
pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl");
pro.setProperty("user", "sa");
pro.setProperty("pwd", "sasa");
try {
//存储到绝对路径D:\\Personal\\Desktop\\IO\\File\\demo\\readme2.txt
//pro.store(new FileOutputStream(new File("D:\\Personal\\Desktop\\IO\\File\\demo\\db.properties")), "db配置");
//pro.storeToXML(new FileOutputStream(new File("D:\\Personal\\Desktop\\IO\\File\\demo\\db.xml")), "db配置");
//在工作中,我们一般把配置文件和项目放在一起,使用相对路径(默认是当前工程)
//pro.store(new FileOutputStream(new File("db.properties")), "db配置");
//保存到src下
//pro.store(new FileOutputStream(new File("src/db.properties")), "db配置");
//保存到包下面
pro.store(new FileOutputStream(new File("src/com/mipo/collection/db.properties")), "db配置");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//使用Properties读取配置文件
public static void test3() {
Properties pro = new Properties();
try {
//读取文件(绝对路径)
//pro.load(new FileReader("D:\\Personal\\Desktop\\IO\\File\\demo\\db.properties"));
//读取文件(相对路径)
pro.load(new FileReader("src/com/mipo/collection/db.properties"));
System.out.println(pro.getProperty("user"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//使用类相对路径读取配置文件,该方法工作中常用
public static void test4 () {
Properties pro = new Properties();
try {
//类相对路径(/表示bin目录)
//pro.load(TestProperties.class.getResourceAsStream("/com/mipo/collection/db.properties"));
//类加载器(""表示bin目录)
pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/mipo/collection/db.properties"));
System.out.println(pro.getOrDefault("user", "用户"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Properties类(读写资源配置文件)
最新推荐文章于 2022-02-20 11:34:27 发布