为什么使用【Properties】读取含【中文】的【配置文件】会【乱码】

问题:

在开发中,为了随时修改方便属性和加密一些账户密码,会把私密信息写到配置文件,然后从配置文件中读取,这个过程中一般会使用java中的new Properties()

一般使用【仅含英文】:

定义工具类:
package com.bigdata.Utils

import java.io.{BufferedReader, InputStreamReader}
import java.text.SimpleDateFormat
import java.util.{Date, Properties}

class PropertiesUtil(fileName:String) {

  var properties:Properties = null

  def getProp() ={
    if(properties==null){

      properties = new Properties()
      properties.load(this.getClass.getClassLoader.getResourceAsStream(fileName))

      properties
    }else{
      properties
    }
  }
}

读取配置:
private val ppUtil = new PropertiesUtil("bigdata.properties").getProp()

println(ppUtil.getProperty("data"))

读取异常:

在读取中文的时候,这个方法就可不用了,读取出来的信息大多是??,有时候因为文件编码的不同可能是其他西方国家的文字,反正看不懂就是了。这个时候就需要下面的步骤来实现读取中文了:

读取中文使用:

//下面我使用了UTF-8文件格式,这里如果你想要本地使用的话,也需要将配置文件的编码格式修改为UTF-8

我是使用sublime修改的:在这里插入图片描述

package com.bigdata.Utils

import java.io.{BufferedReader, InputStreamReader}
import java.text.SimpleDateFormat
import java.util.{Date, Properties}

class PropertiesUtil(fileName:String) {

  var properties:Properties = null

  def getProp() ={
    if(properties==null){

      properties = new Properties()

      properties.load(new BufferedReader(new InputStreamReader(this.getClass.getClassLoader.getResourceAsStream(fileName),"UTF-8")))

      properties
    }else{
      properties
    }
  }
}

调用方式和上面写过的是一样的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值