Java读取.properties文件

前言:简单地记录自己是如何用Java读取.properties文件的,可以说没什么技术含量的。。。

 

方法一:

 

Properties prop = new Properties();
InputStream is = Object.class.getResourceAsStream("/test.properties");
prop.load(is);

 需要catch或者抛出IOException。

 

方法二:

 

Properties prop = new Properties();
InputStream is = Object.class.getResourceAsStream("/test.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
prop.load(br);

 同样需要catch或者抛出IOException。

 

方法二与方法一不同之处是方法二可以读取.properties中的中文,如果.properties中有中文的话就需要用到方法二了,当然.properties文件的编码方式应改为UTF-8。

 

eclipse中修改.properties文件的编码方式是右键点.properties文件,然后选“Properties”,在“Resource”中的“Text file encoding”中选择UTF-8,OK后在弹出的警告框中点“确定”就可以了。.properties文件需要单独修改编码方式,即使项目编码方式改为UTF-8,但是.properties文件的编码方式还是不会变的,所以需要单独修改。

 

.properties文件直接放在Source Folder下面,如下图所示。图中的项目是maven的webapp项目,图中的src/main/java是项目Source Folder,.properties文件都在里面,org.mms.util包中存放读取./properties的类。


 

完整的读取.properties文件的类如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @author Ethan.Lu
 *
 */
public class PropertiesUtil {

	private static String test;   // 测试
	
	static {
		try {
			Properties prop = new Properties();
			InputStream is = Object.class.getResourceAsStream("/test.properties");
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			prop.load(br);
			
			test = prop.getProperty("test");   //获取test的值
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
        // 通常这个类都是static,所以构造函数设为private
	private PropertiesUtil () {}

	/**
	 * @return the test
	 */
	public static String getTest() {
		return test;
	}
}

 

test.properties中写进:

# test
test=测试

 

然后就可以写测试类来测试是否成功了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值