如果你的Properties含有變數串接變數的話,
例如:
IP=192.168.0.1
URL=http:/{IP}/WebServer
可以使用這個擴展的XProperties。
星期四, 3月 22, 2012
星期一, 12月 06, 2010
[Java] Java如何讀取與寫入properties file Reading and Writing a Properties File
try {
properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}
// Write properties file.
try {
properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}
上面寫法路徑一直讓我讀不到,採用package path是正確可以讀到的
資源的package path:local.my.properties
String repositoryLocation = null;
// create an instance of properties class
Properties props = new Properties();
URL url = Thread.currentThread().getContextClassLoader().getResource("local/my.properties");
try {
props.load(url.openStream());
// props.load(in);
repositoryLocation = props.getProperty(propertyName);
System.out.println("property:" + repositoryLocation);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return repositoryLocation;
後記:2012/03/22
使用以上作法會造成to many file open的議題產生(開檔後未關檔),不應該每要一個屬性就開properties檔案一次。可參考以下解法:
loading properties file from java package
When loading the Properties from a Class in the package
com.al.common.email.templates you can useProperties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close()
(Add all the necessary exception handling).
If your class is not in that package, you need to aquire the InputStream slightly differently:
InputStream in = getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
Relative paths (those without a leading '/') in
getResource()/getResourceAsStream() mean that the resource will be searched relative to the directory which represents the package the class is in.
Using
java.lang.String.class.getResource("foo.txt") would search for the (inexistent) file/java/lang/String/foo.txt on the classpath.
Using an absolute path (one that starts with '/') means that the current package is ignored.
Reference:
Java Properties file examples
訂閱:
意見 (Atom)