java 读取配置文件工具_java读取配置文件信息properties的工具类

java读取配置文件信息properties的工具类,介绍一个工具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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值