如何解析属性文件中的属性值

gir*_*iri 1 java properties-file

嗨,我正在加载属性文件以建立数据库连接,例如:

DB1="JDBc................", username , password
Run Code Online (Sandbox Code Playgroud)

上面的行就像属性文件一样,但是当我调用getConnection方法时,我需要发送url,username和pw.我该如何解析它.

Cha*_*dNC 8

您可以将键/值对放在属性文件中,如下所示:

dbUrl = yourURL
username = yourusername
password = yourpassword
Run Code Online (Sandbox Code Playgroud)

然后,您可以从属性文件将它们加载到您的应用程序中:

private void loadProps() {
    try {
        InputStream is = getClass().getResourceAsStream("database_props.properties");
        props = new Properties();
        props.load(is);
        is.close();
        dbConnStr = props.getProperty("dbUrl");
        username = props.getProperty("username");
        password = props.getProperty("password");
    }
    catch(IOException ioe) {
        log.error("IOException in loadProps");
        for(StackTraceElement ste : ioe.getStackTrace())
        log.error(ste.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用这些值来创建连接.