星期一, 12月 06, 2010

[Java] Java如何讀取與寫入properties file Reading and Writing a Properties File

Properties properties = new Properties();
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 use
Properties 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

1 則留言:

  1. The Spring Framework is a lightweight framework for developing Java enterprise applications. It provides high performing, easily testable and reusable code. Spring handles the infrastructure as the underlying framework so that you can focus on your application.Spring is modular in design, thereby making creation, handling and linking of individual components so much easier. Spring implements Model View Container(MVC) design pattern.
    spring mvc validation example

    回覆刪除

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails