1.jsp页面展示代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="bean.*"%>
<%
User user=(User)request.getAttribute("user");
%>
读取property文件
读取proper文件
姓名 <%= user.getUserName()%> 英名 <%=user.getUserEnName()%> 部门 <%=user.getDepartment()%>
2. 代码结构图
其中common中的Prop.java是读取properties文件
3.代码实现
一.初版
public class Prop {
private Properties proper;
public Prop(String fileName) throws IOException {
proper = new Properties();
proper.load(Prop.class.getResourceAsStream(fileName));
}
/**
* 获取properties值
*
* @param key
* @return
*/
public String getValue(String key) {
return proper.getProperty(key);
}
}
通过上述方法能够实现读出properties文件中的内容。但是存在两个缺陷
1. class.gerResourceAsStream()方法默认路径是当前类路径。对于不同的properties文件必须放在此类目录下/或者写完整路径。
2. inputStream没有定义编码方式,如果properties中的文字是中文的。则会出现乱码
3. inputStream 异常不应当抛出,而应该在此类中捕获。
二. 修正
系统加载器,类加载器,当前线程的上下文加载器。通过线程的上下文加载器
Thread.currentThread.getContextClassLoader()来查找这个文件
代码如下:
public class Prop {
private Properties proper;
private static final String CODE_STYLE = "UTF-8";
/**
* 默认UTF-8编码
* @param fileName
*/
public Prop(String fileName) {
this(fileName, CODE_STYLE);
}
/**
* 自定义编码
* @param fileName
* @param codeStyle
*/
public Prop(String fileName, String codeStyle) {
proper = new Properties();
InputStream inputStream = null;
try {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
if (null == inputStream) {
throw new IllegalArgumentException("properties file" + fileName + "not found");
}
proper.load(new InputStreamReader(inputStream, codeStyle));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取properties值
*
* @param key
* @return
*/
public String getValue(String key) {
return proper.getProperty(key);
}
}
三. 增加缓存
文件读取涉及IO流的操作。增加缓存机制
新增PropUtil.java
public class PropUtil {
private static Prop prop;
// 线程安全Map
private static Map
cacheProp = new ConcurrentHashMap
();
public static Prop load(String fileName) {
return load(fileName, prop.CODE_STYLE);
}
/**
* 加载properties文件
*
* @param fileName
* @param codeStyle
* @return
*/
public static Prop load(String fileName, String codeStyle) {
prop = cacheProp.get(fileName);
if (null == prop) {
prop = new Prop(fileName);
cacheProp.put(fileName, prop);
}
return prop;
}
public static void unLoad(String fileName) {
prop = cacheProp.get(fileName);
if (null != prop) {
cacheProp.remove(fileName);
prop = null;
}
}
}