问题:
在开发中,为了随时修改方便属性和加密一些账户密码,会把私密信息写到配置文件,然后从配置文件中读取,这个过程中一般会使用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
}
}
}
调用方式和上面写过的是一样的。