今天在写代码的过程中遇到一个问题,跟大家讨论讨论.
properties配置文件中的中文注释全是ascii码形式的,看不懂,就想写段代码来转换成gbk或utf-8形式的中文:
public static String ascii2ChineseDesc(String asciiStr){
if(asciiStr==null){
return "传入的字符串为空!";
}
return new String(asciiStr.getBytes());
}
在调用传参的时候传入ascii码字符串参数,能正确显示为中文.就这样凑合用着.
后来发现配置文件中的中文注释太多,这样一段一段的转换太费时了,所以干脆就用io流来读取配置文件,每读一行就调用
上面的方法一次来转换成中文.
while ((res = reader.readLine()) != null) {
buf.append(new String(res.getBytes()) + "\n");
}
最后打印buf.toString()时,那些ascii码没有被转换成中文.试了一些方法都不行,如果你直接给定一个字符串,比如
String str = "\u5206\u5272";
然后System.out.println(new String(str.getBytes()));它还是能转换成中文,但是只要是通过BufferedReader读出来的
就是转换不了.我想是不是由于properties文件编码的问题(默认是:ISO-8859-1),目前还没有解决这个问题.希望在论坛上大家都能
讨论一下.
IO流读取源码:
public static String getPropFileChineseDES(String fileName) {
/**
* 把字节流转换为字符流,InputStreamReader是字节流与字符流转换的桥梁
*/
InputStream stream = CommonDemo.class.getClassLoader().getResourceAsStream(fileName);
InputStreamReader in = new InputStreamReader(stream);
BufferedReader reader = new BufferedReader(in);
BufferedWriter writer = null;
String res = "---------------------------文件[" + fileName+ "]---------------------------\n";
StringBuffer buf = new StringBuffer(res);
try {
File f = new File("info.txt");
writer = new BufferedWriter(new FileWriter("info.txt"));//相对路径:相对于工程根目录来说
while ((res = reader.readLine()) != null) {
buf.append(new String(res.getBytes()) + "\n");
}
writer.write(buf.toString());
writer.flush();
System.out.println(f.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}finally{
try {
if(reader!=null){
reader.close();
}
if(writer!=null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return buf.toString();
}