读中文文件,防止乱码(用字符流)

来源:互联网 发布:java中compare函数 编辑:程序博客网 时间:2024/05/29 10:16
从文本中读入文件时,要是文本存在中文,用字节流的形式读取文件,即使写入如下代码: 

Java代码  收藏代码
  1. StringBuffer sqlSb = new StringBuffer();  
  2.             byte[] buff = new byte[1024];  
  3.             int byteRead = 0;  
  4.             while ((byteRead = sqlFileIn.read(buff)) != -1) {  
  5.                   
  6.                 sqlSb.append(new String(buff, 0, byteRead));  
  7.             }  
  8.              String temp2 = new String(sqlSb.toString().getBytes("UTF-8"), "UTF-8");    
  9.              System.out.println("读出文件信息:"+temp2);  

这样进行了字符集的改变,但也不能正确读取文件中的中文。而文本中都是字符串类型的数据,所以可以用字符流读取文件,代码如下: 
Java代码  收藏代码
  1. File file=new File(sqlFile);  
  2.          BufferedReader reader = null;  
  3.          reader = new BufferedReader(new FileReader(file));  
  4.          String str = null;  
  5.          while ((str = reader.readLine()) != null) {  
  6.                System.out.println(str);  
  7.                sqlSb.append(str+"\r\n");  
  8.              }  


所以,当要读取文本中存在中文的文本时,最好要用字符流读取文件!

 一定要记得关闭流,它会释放文件句柄并允许其他人访问文件。

转载自:http://panlianghui-126-com.iteye.com/blog/1472191

0 0
原创粉丝点击