问题的提出:初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题
问题分析:开始以为是文件保存编码问题,把eclipse中所有的文件编码都修改成utf8,问题依然存在;把内容复制到notepad++进行utf8编码转换,问题依旧;上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,嫌麻烦而且凭感觉jdk开发者不可能不考虑东亚几国的字符编码问题;因为properties文件操作的代码是参考百度文库里的一边文章的,分析其代码后,发现其用的是字节流来读取文件,具体代码如下:
因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。代码如下:
问题分析:开始以为是文件保存编码问题,把eclipse中所有的文件编码都修改成utf8,问题依然存在;把内容复制到notepad++进行utf8编码转换,问题依旧;上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,嫌麻烦而且凭感觉jdk开发者不可能不考虑东亚几国的字符编码问题;因为properties文件操作的代码是参考百度文库里的一边文章的,分析其代码后,发现其用的是字节流来读取文件,具体代码如下:
- Properties properties = new Properties();
- InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");
- properties.load(inputStream );
- System.out.println(properties.getProperty("a"));
因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。代码如下:
- Properties properties = new Properties();
- InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");
- BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
- properties.load(bf);
- System.out.println(properties.getProperty("a"));
转换为string(ISO8859-1 -> utf-8)
import
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.util.Properties;
public
class
CP {
private
static
final
String path =
"config/common.properties"
;
//从src的根目录开始
private
static
final
String encode =
"UTF-8"
;
//文件的编码格式
private
static
Properties props =
new
Properties();
static
{
try
{
props.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream(path));
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
public
static
String getValue(String key)
throws
Exception {
return
new
String(props.getProperty(key).getBytes(
"ISO8859-1"
), encode);
}
public
static
void
updateProperties(String key, String value) {
props.setProperty(key, value);
}
public
static
void
main(String[] args)
throws
Exception{
System.out.println(
"网站名称:"
+CP.getValue(
"site"
));
}
}