在windows下判断一个文件的编码类型,可以使用下面你方式:
方法1:扩展方案
# 通过choco安装file命令(需先安装Chocolatey) choco install file -y # 使用file命令检测编码 file --mime-encoding C:\test.txt
方法2:通过字节序标记(BOM)快速判断
# 读取文件前4个字节并分析BOM function Get-FileEncoding($Path) { $bytes = [byte[]](Get-Content -Path $Path -Encoding Byte -ReadCount 4 -TotalCount 4) if ($bytes[0] -eq 0xef -and $bytes[1] -eq 0xbb -and $bytes[2] -eq 0xbf) { return 'UTF8-BOM' } elseif ($bytes[0] -eq 0xff -and $bytes[1] -eq 0xfe) { return 'UTF16-LE' } # Unicode elseif ($bytes[0] -eq 0xfe -and $bytes[1] -eq 0xff) { return 'UTF16-BE' } # Big-Endian elseif ($bytes[0] -eq 0x2b -and $bytes[1] -eq 0x2f -and $bytes[2] -eq 0x76) { return 'UTF7' } else { return 'ANSI/UTF8-NO-BOM' } # 可能为ANSI或UTF8无BOM } # 使用示例 Get-FileEncoding -Path "C:\test.txt"