牛骨文教育服务平台(让学习变的简单)
博文笔记

Bom头的检测

创建时间:2016-06-04 投稿人: 浏览次数:822

什么是bom头?

在utf-8编码文件中BOM在文件头部,占用三个字节,用来标示该文件属于utf-8编码,现在已经有很多软件识别bom头,但是还有些不能识别bom头,比如PHP就不能识别bom头,这也是用记事本编辑utf-8编码后执行就会出错的原因了。

----------------------------------分割线----------------------------------


看是否带Bom,可以用notepad++,但是如果有一大批文件,要挨个查看编码,就有点恶心了,所以这事交给代码来做吧,例子如下:


using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;

public class CfgBomCheck 
{
    [MenuItem("GameTools/检测配置表BOM头")]
    public static void CheckCfgBom()
    {
        checkBom(GetEssentialConfigFiles());
    }

    static string[] GetEssentialConfigFiles()
    {
        string dir_name = Application.dataPath + "/RawAssets/EssentialConfig/";
        return System.IO.Directory.GetFiles(dir_name, "*.bytes", System.IO.SearchOption.AllDirectories);
    }

    static void checkBom(string[] files)
    {
        foreach (var f in files)
        {
            System.IO.FileStream fs = new System.IO.FileStream(f, FileMode.Open, FileAccess.Read);
            using (fs)
            {
                System.IO.BinaryReader rd = new System.IO.BinaryReader(fs);
                using (rd)
                {
                    byte[] bs = rd.ReadBytes(3);
                    if (bs[0] == 0xef && bs[1] == 0xbb && bs[2] == 0xbf)
                    {
                        DebugLog.LogError(string.Format("配置表有BOM头,文件:{0}", f));
                    }
                }
            }
        }
    }
}


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。