java文件读取的时候有中文就很出现乱码,通常获取到的文件中通常都是“iso8859-1”格式,需要转换为“UTF-8”格式。
如:String str = new String(str.getByte("iso8859-1"),"UTF-8");进行下强制转换后在进行读取即可。
备注:通常格式有GBK、UTf-8、iso8859-1、GB2312,如果上面的强制转换不成功,依次进行这些格式的尝试,肯定是可以解决问题的。
中文乱码代码
public static String readFile(String strFile){
String code = "";
try{
InputStream is = new FileInputStream(strFile);
int iAvail = is.available();
byte[] bytes = new byte[iAvail];
is.read(bytes);
code = new String(bytes);
// log.info("文件内容:\n" + new String(bytes));
is.close();
}catch(Exception e){
e.printStackTrace();
}
return code;
}
修复后代码:
public static String readFile(String strFile){
String code = "";
try{
InputStream is = new FileInputStream(strFile);
int iAvail = is.available();
byte[] bytes = new byte[iAvail];
is.read(bytes);
code = new String(bytes, "UTF-8");
// log.info("文件内容:\n" + new String(bytes));
is.close();
}catch(Exception e){
e.printStackTrace();
}
return code;
}
code = new String(bytes, "UTF-8");