文章目录
创建属性文件
- 创建属性文件
- 解析属性文件获取数据
- 使用类加载器
- 使用 File 对象
新建 db-oracle.properties , 存放项目必须使用到的参数:
driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@192.168.0.23:1521:htlwk
username = openlab
password = open123
解析属性文件获取数据
使用类加载器
public class ConnectionUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
try {
Properties props = new Properties();
// 获得类加载器
ClassLoader cl = ConnectionUtils.class.getClassLoader();
// 调用类加载器的方法去加载在类路径下的文件
InputStream is = cl.getResourceAsStream
("com/tarena/tts/db.properties");
// 将文件的内容读到props对象中
props.load(is);
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
使用 File 对象
public static void getParam(String fileName) {
Properties props = new Properties();
File file = new File(fileName);
try {
// 读入 fileName 指定的文件
FileInputStream fileInputStream = new FileInputStream(file);
// 加载解析输入流指定的文件
props.load(fileInputStream);
// 获取文件中键值对的值,并赋值给全局变量
url = props.getProperty("url");
dbUser = props.getProperty("dbUser");
dbPassword = props.getProperty("dbPassword");
driver = props.getProperty("driver");
} catch (IOException e) {
e.printStackTrace();
}
}