java 读取包含[BOM]位的UTF-8文件
2016-09-05 00:00
393 查看
摘要: UTF-8编码的文件在读取时要格外注意,看其文件开头是否包含[BOM]位。
最近在做一个数据共享的项目,在读取UTF-8编码的文件时出现些问题,现记录如下。
UTF-8编码的文件在读取时要格外注意,看其文件开头是否包含[BOM]位。
这个字符一般用来判断该文件是否为UTF-8编码,但Java读取时也会将该判断位一同读出,导致读取的数据与预期不一致。
解决方法如下
最近在做一个数据共享的项目,在读取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格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java对UTF-8格式文件的读取、写入及添加BOM头处理
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式文件第一行出现乱码——问号“?”及解决 And Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取带有BOM的UTF-8文件乱码原因及解决办法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式文件第一行出现乱码——问号“?”及解决 And Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- Java读取文件夹下的指定类型的文件(包含子文件夹)
- JAVA从UTF-8编码文件读取字符串时,前边有问号的问题
- java读取配置文件转为UTF-8
- Java中对有BOM头的UTF-8文件的处理
- Java正确判别出文件的字符集(尤其是带BOM和不带BOM的UTF-8字符)
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决
- java utf-8文件的读取
- 替换Java文件的utf-8 BOM