栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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
    }
  }
}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666748.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号