如何把 className、url、user、password写入资源配置文件中?

xiaoxiao2021-02-28  41

一、在当前java工程 src下右键新建 一个file,起名 db.properties ,

双击打开该文件,properties是Map的一个子类,所以配置文件中的数据以键值对形式保存。

如果显示的是文档格式,在文件上 右键 open with - MyEclipse Properties Editor,这样看起来更简洁点。

点击右侧的add添加,key填写String类型的变量名,value填写实际用到的字符串值(如:要连接的url等)。

二、在工具类的ConnOrcl.java中加载配置文件。

第一种方式:在static初始化块中加载,利用当前线程的类加载器中的输入流读进来。

static Properties pros=null; static{ //加载配置文件 pros = new Properties(); try { pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties")); } catch (IOException e) { e.printStackTrace(); } }

第二种方式:通过 FileInputStream 读进来。

static

{

try

{

Properties props = new Properties();

FileInputStream in = new FileInputStream("src/oracle.ini");

props.load(in);

in.close();

String drivers = props.getProperty("driver");

String url = props.getProperty("url");

String username = props.getProperty("user");

String password = props.getProperty("pass");

//加载数据库驱动

Class.forName(drivers);

//取得数据库连接

conn = DriverManager.getConnection(url, username, password);

stmt = conn.createStatement();

}

catch (Exception e)

{

e.printStackTrace();

}

}

三、加载驱动,获取连接

//1.加载驱动 try { Class.forName(pros.getProperty("className")); } catch (ClassNotFoundException e) { System.out.println("类找不到"); e.printStackTrace(); } //2.获取连接 try { conn = DriverManager.getConnection(pros.getProperty("url"), pros.getProperty("user"), pros.getProperty("password")); } catch (SQLException e) { System.out.println("获取连接失败"); e.printStackTrace(); }

执行完上述三个步骤,就可以把配置文件读取进来,修改时只需要修改db.properties文件,不需要修改代码,符合OCP原则。

转载请注明原文地址: https://www.6miu.com/read-57117.html

最新回复(0)