您当前的位置: 首页 > 

liaowenxiong

暂无认证

  • 0浏览

    0关注

    1171博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

如何解析属性文件(properties)获取键值对的值?

liaowenxiong 发布时间:2021-03-21 20:05:20 ,浏览量:0

文章目录
  • 创建属性文件
  • 解析属性文件获取数据
    • 使用类加载器
    • 使用 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();
        }
    }
关注
打赏
1661566967
查看更多评论
立即登录/注册

微信扫码登录

0.0403s