您的位置:首页 > 编程语言 > Java开发

java 读取包含[BOM]位的UTF-8文件

2016-09-05 00:00 393 查看
摘要: UTF-8编码的文件在读取时要格外注意,看其文件开头是否包含[BOM]位。

最近在做一个数据共享的项目,在读取UTF-8编码的文件时出现些问题,现记录如下。

UTF-8编码的文件在读取时要格外注意,看其文件开头是否包含[BOM]位。
这个字符一般用来判断该文件是否为UTF-8编码,但Java读取时也会将该判断位一同读出,导致读取的数据与预期不一致。

解决方法如下

import java.io.*;
public class Test1 {
/** 定义BufferReader */
public static BufferedReader  openTextFileR(
String fileName
,String charSet
)throws Exception{
return new BufferedReader(
new InputStreamReader(
skipUTF8BOM(
new FileInputStream(
new File(fileName))
,charSet)
,charSet));
}
/** 跳过[BOM]位 */
public static InputStream skipUTF8BOM(
InputStream is
,String      charSet
)throws Exception{
if( !charSet.toUpperCase().equals("UTF-8") ) return is;
if( !is.markSupported() ){
//   如果输入流不支持mark功能时,用BufferedInputStream替换InputStream
is= new BufferedInputStream(is);
}
is.mark(3); // 标记先头三位
if( is.available()>=3 ){
byte b[]={0,0,0};
is.read(b,0,3);
if( b[0]!=(byte)0xEF ||
b[1]!=(byte)0xBB ||
b[2]!=(byte)0xBF ){
is.reset();// 如果文件不含有[BOM]位时,将文件指针复位
}
}
return is;
}
public static void main(String[] args_){
try{
String         line;
BufferedReader br;
// 无[BOM]处理
br = new BufferedReader(new InputStreamReader(
new FileInputStream(
new File(args_[0]))
,"utf-8"));
while( (line=br.readLine())!=null ) System.out.println(line);
br= new BufferedReader(new InputStreamReader(
new FileInputStream(
new File(args_[1]))
,"utf-8"));
while( (line=br.readLine())!=null ) System.out.println(line);
// 有[BOM]处理
br= openTextFileR(args_[0],"utf-8");
while( (line=br.readLine())!=null ) System.out.println(line);
br= openTextFileR(args_[1],"utf-8");
while( (line=br.readLine())!=null ) System.out.println(line);
}
catch(Exception e){
e.printStackTrace(System.err);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java utf-8
相关文章推荐