在idea中使用java读取properties乱码的解决 |
您所在的位置:网站首页 › 智利邮政官网网址是什么啊 › 在idea中使用java读取properties乱码的解决 |
读取properties的方法是参考网友:五种方式让你在java中读取properties文件内容不再是难题
代码如下: package com.ufgov.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Desc:properties文件获取工具类 * Created by lihhz on 2017/7/4. */ public class PropertyUtil { private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class); private static Properties props; static{ loadProps(); } synchronized static private void loadProps(){ logger.info("开始加载properties文件内容......."); props = new Properties(); InputStream in = null; try { //第一种,通过类加载器进行获取properties文件流 in = PropertyUtil.class.getClassLoader().getResourceAsStream("conf/cpaf-message.properties"); //第二种,通过类进行获取properties文件流 //in = PropertyUtil.class.getResourceAsStream(""); props.load(in); } catch (FileNotFoundException e) { e.printStackTrace(); logger.error("cpaf-message.properties文件未找到"); } catch (IOException e) { logger.error("出现IOException"); e.printStackTrace(); } finally { try { if(null != in) { in.close(); } } catch (IOException e) { logger.error("cpaf-message.properties文件流关闭出现异常"); e.printStackTrace(); } } logger.info("加载properties文件内容完成..........."); logger.info("properties文件内容:" + props); } public static String getProperty(String key){ if(null == props) { loadProps(); } return props.getProperty(key); } public static String getProperty(String key, String defaultValue) { if(null == props) { loadProps(); } return props.getProperty(key, defaultValue); } public static void main(String[] args) throws Exception{ //ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(getProperty("cpaf_app_again_90"));//äºå¡æ设ç«ç³è¯·ï¼%sï¼éæ°æ¹åä¸éè¿ï¼è¯·åæ¶å°çè´¢æ¿é¨é¨é¢åç¸å ³æ件ã System.out.println(new String(getProperty("cpaf_app_again_90").getBytes("iso-8859-1"),"utf-8"));//请及时到省财政部门领取相关文件。 System.out.println("戴假发");//戴假发 } } 如上,在main方法中的乱码,但是使用ISO-8859-1,打印结果却是正常的。
好久没有遇到过乱码问题了,查了一些资料,找到一些有用的内容记录一下
1.idea中properties的编码设置
2. in = PropertyUtil.class.getClassLoader().getResourceAsStream("conf/cpaf-message.properties");读取的是字节流,但是中文是无法使用字节流而必须使用字符流的,所以,props.load(in);改为props.load(new InputStreamReader(in));即可,读取出来的内容就正常了.
|
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |