通常,通用类会从静态上下文读取属性文件,这下面是一个例子
mport
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.io.InputStream;
import
java.util.Properties;
public
class
MyPropInStaticBlock {
private
static
Properties prop;
static
{
InputStream is =
null
;
try
{
prop =
new
Properties();
is = ClassLoader.
class
.getResourceAsStream(
"/sample.properties"
);
prop.load(is);
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
public
static
String getPropertyValue(String key){
return
prop.getProperty(key);
}
public
static
void
main(String a[]){
System.out.println(
"db.host: "
+getPropertyValue(
"db.host"
));
System.out.println(
"db.user: "
+getPropertyValue(
"db.user"
));
System.out.println(
"db.password: "
+getPropertyValue(
"db.password"
));
}
}
sample.properties |
1
2
3
4
|
db.host=appdomain.java2novice.com
db.user=java2novice
db.password=mypassword
db.service=orcl
|
|
Output: |
db.host: appdomain.java2novice.com
db.user: java2novice
db.password: mypassword |