java读取配置文件

来源:互联网 发布:ubuntu打开软件更新器 编辑:程序博客网 时间:2024/05/16 18:37

读取config.properties配置文件里传入参数为keyName的值

PropertiesReader类的代码如下

import java.io.*;

import java.util.*;


public class PropertiesReader {
public static String getProperties(String keyName) {
String keyValue = null;
//System.out.println(keyName);
try {
InputStream in = PropertiesReader.class.getClassLoader().getResourceAsStream("config.properties");//读取配置文件对象
Properties format = new Properties();//读取文件的格式对象.
format.load(in);//将文件的读取对象和文件的读取格式对象,相关联.
keyValue = format.getProperty(keyName);
//System.out.println(keyValue);
} catch (Exception e) {
e.printStackTrace();
}
return keyValue;
}

}


配置文件config.properties内容如下

db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
db.uname=scott
db.uword=orcl


主函数Test如下

public class Test {
public static void main(String[] args) {
String driver = PropertiesReader.getProperties("db.driver");
String url = PropertiesReader.getProperties("db.url");
String uname  = PropertiesReader.getProperties("db.uname");
String uword  = PropertiesReader.getProperties("db.uword");

System.out.println(driver);
System.out.println(url);
System.out.println(uname);
System.out.println(uword);
}


}


结果输出如下

oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@127.0.0.1:1521:orcl
scott
orcl

原创粉丝点击