如何解析属性文件(properties)获取键值对的值?
生活随笔
收集整理的這篇文章主要介紹了
如何解析属性文件(properties)获取键值对的值?
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 創(chuàng)建屬性文件
- 解析屬性文件獲取數(shù)據(jù)
- 使用類加載器
- 使用 File 對(duì)象
創(chuàng)建屬性文件
新建 db-oracle.properties , 存放項(xiàng)目必須使用到的參數(shù):
driver = oracle.jdbc.driver.OracleDriver url = jdbc:oracle:thin:@192.168.0.23:1521:htlwk username = openlab password = open123解析屬性文件獲取數(shù)據(jù)
使用類加載器
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();// 調(diào)用類加載器的方法去加載在類路徑下的文件InputStream is = cl.getResourceAsStream("com/tarena/tts/db.properties");// 將文件的內(nèi)容讀到props對(duì)象中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 對(duì)象
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);// 獲取文件中鍵值對(duì)的值,并賦值給全局變量url = props.getProperty("url");dbUser = props.getProperty("dbUser");dbPassword = props.getProperty("dbPassword");driver = props.getProperty("driver");} catch (IOException e) {e.printStackTrace();}}總結(jié)
以上是生活随笔為你收集整理的如何解析属性文件(properties)获取键值对的值?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 糖果手机是哪个公司生产的(糖果手机是哪个
- 下一篇: IntelliJ IDEA for Ma