在用ParameterTool获取参数时,会出现中文乱码的问题。如下获取ParameterTool的方法getParameterTool:
/**
* 获取配置信息
* @param filePath 配置文件路径
* @return ParameterTool
*/
public static ParameterTool getParameterTool(String filePath){
ParameterTool parameter = null;
try {
parameter = ParameterTool.fromPropertiesFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
return parameter;
}
配置文件内容为:
name=小辉是小白
测试代码:
public static void main(String[] args) {
ParameterTool parameterTool = getParameterTool("src/main/resources/test.properties");
System.out.println(parameterTool.get("name"));
}
输出结果:
解决:
查看ParameterTool源码发现最终读取文件的操作为:
/**
* Returns {@link ParameterTool} for the given InputStream from {@link Properties} file.
*
* @param inputStream InputStream from the properties file
* @return A {@link ParameterTool}
* @throws IOException If the file does not exist
* @see Properties
*/
public static ParameterTool fromPropertiesFile(InputStream inputStream) throws IOException {
Properties props = new Properties();
props.load(inputStream);
return fromMap((Map) props);
}
这里的参数InputStream是文件的字节流,而中文转成字节流时可能会出现乱码的问题。为了解决这个问题,将字节流转成字符流InputStreamReader。源码里关于InputStreamReader的介绍:
An InputStreamReader is a bridge from byte streams to character streams
然后Properties加载这个字符流,再通过ParameterTool.fromMap方法创建ParameterTool
/**
* Returns {@link ParameterTool} for the given map.
*
* @param map A map of arguments. Both Key and Value have to be Strings
* @return A {@link ParameterTool}
*/
public static ParameterTool fromMap(Map<String, String> map) {
Preconditions.checkNotNull(map, "Unable to initialize from empty map");
return new ParameterTool(map);
}
修改后的getParameterTool为:
/**
* 获取配置信息
* @param filePath 配置文件路径
* @return ParameterTool
*/
public static ParameterTool getParameterTool(String filePath){
ParameterTool parameter = null;
try {
Properties props = new Properties();
InputStream inputStream = new FileInputStream(filePath);
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
props.load(bf);
parameter = ParameterTool.fromMap((Map) props);
} catch (IOException e) {
e.printStackTrace();
}
return parameter;
}
测试结果: