当前位置: 代码迷 >> 综合 >> Properties类(读写资源配置文件)
  详细解决方案

Properties类(读写资源配置文件)

热度:90   发布时间:2023-09-20 23:25:24.0
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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();}}}

  相关解决方案