zoukankan      html  css  js  c++  java
  • java读取配置文件以及中文乱码问题

    1、概述

    Properties 继承于Hashtable,key和value都是字符串

    2、使用

     1 public class ReadProperties {
     2 
     3     public static void main(String[] args) {
     4         Properties properties = new Properties();
     5         try {
     6             //加载配置文件
     7             properties.load(ReadProperties.class.getClassLoader().getResourceAsStream("application.properties"));
     8             /*遍历配置文件中key和value
     9               for (Map.Entry<Object, Object> entry : properties.entrySet()) {
    10                 System.out.println(entry.getKey() + ":" + entry.getValue());
    11             }*/
    12             //根据key获取value值
    13             System.out.println(properties.getProperty("test.properties"));
    14         } catch (IOException e) {
    15             e.printStackTrace();
    16         }
    17     }
    18 }

    3、中文问题

    默认情况下,properties文件是ISO-8859-1编码的,如果需要有中文的配置文件,我们可以使用eclipse等IDE把配置文件设置为UTF-8编码

     (1)选中配置文件-->右键-->Properties-->text file encoding

     (2)使用上述代码会出现乱码情况,修改为在load配置文件时指定编码格式为UTF-8

    properties.load(new InputStreamReader(ReadProperties.class.getClassLoader().getResourceAsStream("application.properties"), "UTF-8"));

    4、其它外部文件

    根据load的参数可知,我们可以读取外部文件传入,这样就可以java工程配置文件单独放在包外面,不同的环境选用不同的配置

    1 File file = new File("E:\data\application2.properties");
    2 FileInputStream fileInputStream = new FileInputStream(file);
    3properties.load(new InputStreamReader(fileInputStream, "UTF-8"));
  • 相关阅读:
    JMM内存模型
    APUE习题8.7
    整型和字符数组之间的转换(略带进制的转化)
    数据结构学习——shell排序的C语言实现
    Unix环境高级编程学习笔记——fcntl
    Unix环境高级编程学习笔记——dup
    链表
    计算机数值表示
    整数位运算相关操作
    win和linux下控制台界面中停顿X秒的方式
  • 原文地址:https://www.cnblogs.com/xiaoweiv/p/11394130.html
Copyright © 2011-2022 走看看