Java读取properties文件,中文出现乱码问题解决

问题的提出:初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题 
问题分析:开始以为是文件保存编码问题,把eclipse中所有的文件编码都修改成utf8,问题依然存在;把内容复制到notepad++进行utf8编码转换,问题依旧;上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,嫌麻烦而且凭感觉jdk开发者不可能不考虑东亚几国的字符编码问题;因为properties文件操作的代码是参考百度文库里的一边文章的,分析其代码后,发现其用的是字节流来读取文件,具体代码如下: 

Properties properties = new Properties();  
InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");  
properties.load(inputStream );  
System.out.println(properties.getProperty("a"));  

因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。代码如下: 

Properties properties = new Properties();  
InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");  
BufferedReader bf = new BufferedReader(new    InputStreamReader(inputStream));  
properties.load(bf);  
System.out.println(properties.getProperty("a"));  

代码示例:

1、工具类

/**
 * 读取配置文件Properties
 * 
 * @author xl
 *
 */
public class PropertiesUtil {

	private PropertiesUtil() {
	}

	private static class SingletonHolder {
		private final static PropertiesUtil instance = new PropertiesUtil();
	}

	public static PropertiesUtil getInstance() {
		return SingletonHolder.instance;
	}

	/**
	 * 读取key字段,配置文件在classes根路径下xx.properties,在子路径下xx/xx.properties
	 * 
	 * @param file
	 * @param key
	 * @return
	 */
	public String read(String file, String key) {
		InputStream in = getClass().getClassLoader().getResourceAsStream(file);
		BufferedReader bf = new BufferedReader(new InputStreamReader(in)); 
		Properties prop = new Properties();
		String value = "";
		try {
			prop.load(bf);
			value = prop.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}

}

2、使用工具类

/**
	 * 获取properties文件中存放的数据
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPropertiesData")
	@ResponseBody
	public Map<String, Object> getPropertiesData(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		// 获取请求参数
		String key = (String) req.getParameter("key");
		String file = (String) req.getParameter("file");
		// 从配置文件读取key对应的value
		String value = PropertiesUtil.getInstance().read(file, key);
		returnMap.put("data", value);
		// 解析返回结果
		return returnMap;
	}

完!!!

发布了106 篇原创文章 · 获赞 65 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/xialong_927/article/details/89313031