清除UTF-8文件的BOM头
2010-01-20 13:42
302 查看
场景:
和某公司合作,给其提供xml文件。对方回邮件说:“你的文件是不是用写字板之类的编辑工具打开过?以二进制查看的时候文件头部有EF BB BF这3个字节……能否去掉?”
查阅了一些资料,发现这是windows系统自动添加的东西,而且调用.Net类库直接生成文件的方法,只要用utf-8编码,都会有这个东西。太无奈了,只好自己动手去掉这些了。
实现:
和某公司合作,给其提供xml文件。对方回邮件说:“你的文件是不是用写字板之类的编辑工具打开过?以二进制查看的时候文件头部有EF BB BF这3个字节……能否去掉?”
查阅了一些资料,发现这是windows系统自动添加的东西,而且调用.Net类库直接生成文件的方法,只要用utf-8编码,都会有这个东西。太无奈了,只好自己动手去掉这些了。
实现:
/// <summary> /// 清除UTF8文件的BOM头 /// </summary> /// <param name="filePath"></param> /// <returns>是否成功</returns> private static bool ClearBOM( string filePath ) { if( !CheckBOM( filePath ) ) return true; string fileTemp = filePath + ".temp"; using( FileStream fsRead = new FileStream( filePath, FileMode.Open ) ) { // 跳过前三个字节 fsRead.Seek( 3, SeekOrigin.Begin ); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; using( FileStream fsWrite = new FileStream( fileTemp, FileMode.Append, FileAccess.Write ) ) { while( fsRead.Read( buffer, 0, bufferSize ) > 0 ) { fsWrite.Write( buffer, 0, bufferSize ); } fsWrite.Close(); } fsRead.Close(); } // 改名 try { File.Delete( filePath ); File.Move( fileTemp, filePath ); } catch { return false; } return true; } /// <summary> /// 检查是否有BOM头。 /// UTF8文件都有一个3字节的头,为“EF BB BF”(称为BOM--Byte Order Mark) /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static bool CheckBOM( string filePath ) { bool isBOM = false; using( FileStream fsRead = new FileStream( filePath, FileMode.Open ) ) { byte[] buffer = new byte[3]; fsRead.Read( buffer, 0, 3 ); if( 0xef == buffer[0] && 0xbb == buffer[1] && 0xbf == buffer[2] ) isBOM = true; fsRead.Close(); } return isBOM; }
注:时间有限,只考虑功能实现,没有考虑性能效率。
相关文章推荐
- PHP批量删除、清除UTF-8文件BOM头的代码实例
- PHP批量删除、清除UTF-8文件BOM头的代码实例
- Java读取UTF-8格式txt文件第一行出现乱码——问号“?”及解决;Java读带有BOM的UTF-8文件乱码原因及解决方法
- PHP 去掉UTF-8+BOM 文件字节前缀
- 用VBS判断无BOM头的文件是否UTF-8编码
- PHP实现UTF-8文件BOM自动检测与移除实例
- 替换Java文件的utf-8 BOM
- 【分享】Android Studio专用文件转换工具:把ANSI文件批量另存为无BOM的UTF-8文件
- python去utf文件的BOM头部
- 当JSP文件和JS文件编码不一致的问题,以及UTF-8的BOM问题
- Java读带有BOM的UTF-8文件乱码原因及解决方法
- php文件代码采用UTF-8编码的BOM问题
- Java读带有BOM的UTF-8文件乱码 推荐
- excel打开UTF-8编码的CSV文件,添加BOM头后不再乱码
- UTF-8文件的BOM头的来由及去除方法
- Python处理以BOM开头的UTF-8编码文件
- UTF-8格式编码与UTF-8无BOM格式编码的区别(包括java文件)
- BOM与读取UTF-8编码格式文件首行乱码问题
- WordPress主题文件UTF-8 BOM带来的问题及解决方法
- Java读带有BOM的UTF-8文件乱码原因及解决方法