Properties属于Map接口中Hashtable实现类
存取数据时,建议使用setProperty(String key,String value)方法和getProperty(String key)方法。
datasource.properties文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF8
username=root
password=7777
取数据
public class AppTest {
private Logger logger = Logger.getLogger(this.getClass());
@Test
public void testProperties(){
Properties pros = new Properties();
try {
// pros.load(new FileInputStream("D:\\code\\Acoffee-Spring\\spring-02-di\\src\\main\\resources\\datasource.properties"));
pros.load(this.getClass().getClassLoader().getResourceAsStream("datasource.properties"));
String driver = pros.getProperty("driver");
String url = pros.getProperty("url");
String username = pros.getProperty("username");
String password = pros.getProperty("password");
logger.info(driver);
logger.info(url);
logger.info(username);
logger.info(password);
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行结果 :
存数据
@Test
public void testProperties1() {
Properties pros = new Properties();
pros.setProperty("driver", "com.mysql.jdbc.Driver");
pros.setProperty("url", "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF8");
pros.setProperty("username", "root");
pros.setProperty("password", "7777");
FileOutputStream os = null;
try {
os = new FileOutputStream("D:\\code\\WNXA30-Spring\\spring-02-di\\src\\main\\resources\\datasource.properties");
pros.store(os,"datasource configuration");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行结果:
stringProperties:(public Set<String> stringPropertyNames()
)
public class PropertiesTest {
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("tom", "11");
p.setProperty("jack", "12");
p.setProperty("frank", "13");
//stringPropertyNames相当于KeySet()
Set<String> set = p.stringPropertyNames();
for (String key : set) {
String value = p.getProperty(key);
System.out.println(key + ":" + value);
}
}
}
执行结果:
store:将Properties中的键值对储存到配置文件,在idea中,保存信息到配置文件,如果含有中文,会储存为Unicode码(public void store( OutputStream out,string comments)
):
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.setProperty("tom", "11");
p.setProperty("jack", "12");
p.setProperty("frank", "13");
p.store(new FileOutputStream("user.properties"),"acoffee");
}
执行结果:
load:加载配置文件的键值对到Properties对象(public void load(InputStream inStream)
):
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.setProperty("tom", "11");
p.setProperty("jack", "12");
p.setProperty("frank", "13");
p.load(new FileInputStream("user.properties"));
System.out.println(p);
}
执行结果:
list:将数据显示到指定设备
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.load(ClassStreamTest.class.getResourceAsStream("user.properties"));
p.list(System.out);
}
执行结果: