当前位置: 代码迷 >> Java Web开发 >> 请问BufferedReader readLine 编码有关问题
  详细解决方案

请问BufferedReader readLine 编码有关问题

热度:665   发布时间:2016-04-17 10:34:14.0
请教BufferedReader readLine 编码问题
Servlet调用过程中打开一个本地文件(gb2312编码)
Java code
String Data_Path = "/storage/tmp/test.conf";File file = new File(Data_Path);String tmpStr = "";FileReader reader;BufferedReader fileStream;if(file.exists()){reader = new FileReader(Data_Path);fileStream = new BufferedReader(reader);while( null != (tmpStr = fileStream.readLine())){tmpStr = new String(tmpStr.getBytes(), "gb2312");System.out.println("==>" + tmpStr);}


这样输出的中文都是乱码;google到说是readLine 方法返回的字符串是iso-8859-1 编码的,所有我改成
Java code
while( null != (tmpStr = fileStream.readLine())){tmpStr = new String(tmpStr.getBytes("iso-8859-1"), "gb2312");System.out.println("==>" + tmpStr);}


可这样还是乱码,无助中,急需帮助,谢谢!

Ps: 如果说readLine 是跟平台相关的话,那tmpStr.getBytes()也应该得到了原始的字节串了吧,然后再用gb2312重新编码字节串,我想应该能得到正确的字符串,
可事实并不是我想的这样.....


------解决方案--------------------
Java code
while( null != (tmpStr = fileStream.readLine())){System.out.println("==>" + tmpStr);}
------解决方案--------------------
xp上没发现这个问题
------解决方案--------------------
可以改变一下文件方式,下面的方法是替换文本文件中指定的字符串
public static boolean replaceFileContent(File file,String charsetName,String oldChar,String newChar){

BufferedReader in = null;
BufferedWriter out = null;
File tempFile = new File(file.getParentFile().getPath()+File.separator+"_"+file.getName());
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(file),charsetName));
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile),charsetName));
String s;
while((s = in.readLine())!=null){
if(s.indexOf(oldChar)>=0){
s = s.substring(0,s.indexOf(oldChar))+newChar+s.substring(s.indexOf(oldChar)+oldChar.length());
}
out.write(s);
out.newLine();
}
out.flush();
out.close();
in.close();
file.delete();
tempFile.renameTo(file);

} catch (Exception e) {
return false;
}finally{
try{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}catch (Exception e) {
logger.error("关闭文件失败:"+e.getMessage());
return false;
}
}
return true;
}

replaceFileContent(new File("E:\\Templete\\Templete171\\html\\index.html"),"gb2312","${playlist_xml_path}","/test/dd/playList.xml");
------解决方案--------------------
生成图片验证码jsp出现getOutputStream()
------解决方案--------------------
你是不是应该用tmpStr.getBytes(Charset charset)啊,
在String转Byte的时候也是需要编码的
------解决方案--------------------
Java code
tmpStr = new String(tmpStr.getBytes("所读取文件的编码格式"), "工程java文件的编码格式");
------解决方案--------------------
貌似配置文件里面也要改吧web.xml
------解决方案--------------------
我感觉乱码是你的读取有问题 也就是你读的内容有问题 没有完整的读入一行字符 所在解析成乱码
------解决方案--------------------
  相关解决方案