java 如何解析属性文件中的属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4689779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse property value in properties file
提问by giri
Hi I am loading a property file to establish DB connection, ex:
嗨,我正在加载一个属性文件来建立数据库连接,例如:
DB1="JDBc................", username , password
above line is as in property file, but when i call getConnection method I need to send url, username and pw. How can I parse it.
上面的行与属性文件中的一样,但是当我调用 getConnection 方法时,我需要发送 url、用户名和密码。我该如何解析它。
回答by ChadNC
You can put your key/value pairs in a properties file like this:
您可以将键/值对放在属性文件中,如下所示:
dbUrl = yourURL
username = yourusername
password = yourpassword
Then you can load them into your app from the properties file:
然后您可以从属性文件将它们加载到您的应用程序中:
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());
}
}
And then you can use those values to create your connection.
然后您可以使用这些值来创建您的连接。
回答by Nivas
You can split the entry:
String dbProperty = prop.getProperty("DB1"); String[] dbDetails = dbProperty.split(",", 3);
您可以拆分条目:
String dbProperty = prop.getProperty("DB1"); String[] dbDetails = dbProperty.split(",", 3);
dbDetails[0]
will hold your JDBC...
, [1]
your username
and [2]
your password
dbDetails[0]
将举行你的JDBC...
,[1]
你的username
和[2]
你的password
Better still, you might want to hold them in different properties (As lweller said)
db.username = scott db.password = tiger db.url = ....
更好的是,您可能希望将它们保存在不同的属性中(正如 lweller 所说)
db.username = scott db.password = tiger db.url = ....
This way you get better clarity and control.
通过这种方式,您可以获得更好的清晰度和控制力。
回答by fmucar
It is better to define separately
最好分开定义
dburl =....
username =....
password = ...
Still if you want to parse it, you can use the split method of string to split by comma
还是要解析的话,可以使用string的split方法进行逗号分割