- 论坛徽章:
- 0
|
In Eclipse, at runtime, the following piece of code could not work
Properties props = new Properties();
try {
props.load(new FileInputStream("test.properties"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(props.getProperty("test"));
Because eclipse can not recoginze the local file system path even you put the properties file at the same folder as ur java code, and also if we want to write portable Java Code, it is very bad to find resource file this way.
There are other 2 methods to find resource file, one of them is using URL, and the other method is putting resource files at class path, and write the code like below, since eclipse will put src folder at classpath, so it is also a safe way to write at Eclipse
Properties props = new Properties();
InputStream file =
ClassLoader.getSystemResourceAsStream("test.properties");
try{
props.load(file);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(props.getProperty("test"));
And if you want to read more about how to handle resource files smartly. Here is a link to a very good article at javaworld.com
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/2956/showart_272676.html |
|