介绍一个工具PropertyReader.java,读取配置文件信息
package mymail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
*
* 配置文件读取类
* */
public class PropertyReader {
private Properties prop;
private String path;
public PropertyReader(String path) {
this.prop = new Properties();
this.path = path;
try {
InputStream in= PropertyReader.class.getResourceAsStream(this.path);
//FileInputStream in = new FileInputStream(new File(this.path));
this.prop.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return prop.getProperty(key);
}
public void addProperty(String key, String value) {
prop.put(key, value);
}
public Properties getProp() {
return prop;
}
public void setProp(Properties prop) {
this.prop = prop;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
测试这个类有如下2种方法,
public static void main(String[] args) {
//第一种方法调用
PropertyReader reader=new PropertyReader("mail.properties");
// 如下使用
System.out.println(reader.getProperty("send.mail.user"));
System.out.println(reader.getProperty("send.mail.pass"));
// 第二种方法调用
// Properties prop= new Properties();
// prop.put("send.mail.host", "smtp.sina.com");
// prop.put("send.mail.user", "lihostudent@sina.com");
// prop.put("send.mail.addr", "lihostudent@sina.com");
// prop.put("send.mail.pass", "abcdef");
// prop.put("to.mail.addr", "519253688@qq.com");
//
// PropertyReader reader=new PropertyReader();
// reader.setProp(prop);
//
// 如下使用
// reader.getProperty("to.mail.pass") ;
//reader.getProperty("to.mail.user") ;
}
其中我的配置文件mail.properties放在src目录下,
内容如下
send.mail.user=lihong2002.student@sina.com
send.mail.pass=abcdef
如果运行在web项目中,第一种方法调用需要做如下修改:
//第一种方法调用: 用相对路径
PropertyReader reader=new PropertyReader("/mail.properties");
附: 关于详细介绍java获取路径的文章
http://laorer.javaeye.com/blog/118088