public class PropertiesGetting {
private Properties properties;
/*
* A constructor is built.
*/
public PropertiesGetting(String fileName)throws Exception{
properties = new Properties();
System.out.println();
InputStream inputstream=new FileInputStream(fileName);
properties.load(inputstream);
}
/*
* A method for getting a value by a specified key
* is implemented.
*/
public String getValue(String key)throws Exception{
String result;
result=properties.getProperty(key);
if (result==null){
throw new Exception("Getting properties from a property file failure!The key can not be found");
}
return result;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/*
* This class provides a general method to get the
* value of a key from a specified properites file.
*/
public class PropertiesGetting {
private Properties properties;
/*
* A constructor is built.
*/
public PropertiesGetting(String fileName)throws Exception{
properties = new Properties();
//InputStream inputstream=new FileInputStream(fileName);
InputStream inputstream = this.getClass().getResourceAsStream("/"+fileName);
properties.load(inputstream);
inputstream.close();
}
/*
* A method for getting a value by a specified key
* is implemented.
*/
public String getValue(String key)throws Exception{
String result;
result=properties.getProperty(key);
if (result==null){
throw new Exception("Getting properties from a property file failure!The key can not be found");
}
return result;
}
public Properties getProperties(){
return properties;
}
}
这两个类,如果都只是放在eclipse/workspace/project/src的一个包下面,只要把要读取的文件放到src下就没有问题。
但是, 为了日后便于操作,我把这个类文件封装成了一个jar包,作为我的utility。这两个类唯一的区别在于:
InputStream inputstream=new FileInputStream(fileName);
InputStream inputstream = this.getClass().getResourceAsStream("/"+fileName);
打成jar包后,前一种在不同的环境下得到的文件的当前路径不同,比如在ecliipse环境下,如果是java项目则在项目根目录下;如果是j2ee项目则在eclipse目录下(很奇怪!);如果是制作成war包,则应该放到“tomcat”根目录下,并不是tomcat的webapp/projec 下。所以变数很多!
后者相对来说比较固定,就在eclipse的project/src目录下。打成war包应该也不会变(需要测试!)。。。
考虑到项目需要打包,只能把配置文件放到项目根目录下。用如下方法。
//The following method requires the file is in the root directory of project.
String projectAbsolutePath = System.getProperty( "user.dir");
if (System.getProperty("os.name").contains("Windows")) {
fileName = projectAbsolutePath+"\\"+fileName;
}else {
fileName = projectAbsolutePath+"/"+fileName;
}
InputStream inputstream = new FileInputStream(fileName);