UTF-8和UTF-8与BOM有什么不同?哪个更好?


当前回答

Unicode字节顺序标记(BOM)常见问题解答提供了一个简明的答案:

Q: How I should deal with BOMs? A: Here are some guidelines to follow: A particular protocol (e.g. Microsoft conventions for .txt files) may require use of the BOM on certain Unicode data streams, such as files. When you need to conform to such a protocol, use a BOM. Some protocols allow optional BOMs in the case of untagged text. In those cases, Where a text data stream is known to be plain text, but of unknown encoding, BOM can be used as a signature. If there is no BOM, the encoding could be anything. Where a text data stream is known to be plain Unicode text (but not which endian), then BOM can be used as a signature. If there is no BOM, the text should be interpreted as big-endian. Some byte oriented protocols expect ASCII characters at the beginning of a file. If UTF-8 is used with these protocols, use of the BOM as encoding form signature should be avoided. Where the precise type of the data stream is known (e.g. Unicode big-endian or Unicode little-endian), the BOM should not be used. In particular, whenever a data stream is declared to be UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE a BOM must not be used.

其他回答

应该注意的是,对于某些文件,即使在Windows上也不能有BOM。例如SQL*plus或VBScript文件。如果这样的文件包含BOM,则在尝试执行它们时会出现错误。

一个实际的区别是,如果你为Mac OS X编写一个shell脚本,并将其保存为普通的UTF-8,你将得到响应:

#!/bin/bash: No such file or directory

在shebang行指定您希望使用哪个shell的响应中:

#!/bin/bash

如果你保存为UTF-8,没有BOM(说在BBEdit),一切都会很好。

将BOM放在UTF-8编码的文件中至少有三个问题。

不包含文本的文件不再为空,因为它们始终包含BOM。 在UTF-8的ASCII子集中保存文本的文件本身不再是ASCII,因为BOM不是ASCII,这使得一些现有工具无法使用,用户可能不可能替换这些遗留工具。 不可能将几个文件连接在一起,因为现在每个文件开头都有一个BOM。

而且,正如其他人所提到的,使用BOM来检测某些东西是否是UTF-8是既不够也没有必要的:

这是不够的,因为任意字节序列可能恰好以构成BOM的确切序列开始。 这是不必要的,因为你可以像读取UTF-8一样读取字节;如果成功,根据定义,它是有效的UTF-8。

如果你在HTML文件中使用UTF-8,如果你在同一页面上使用塞尔维亚西里尔语、塞尔维亚拉丁语、德语、匈牙利语或一些外来语言,那么使用UTF和BOM更好。

这是我(从事计算机和IT行业30年)的观点。

我从另一个角度看这个问题。我认为UTF-8与BOM更好,因为它提供了更多关于文件的信息。我只在遇到问题时才使用没有BOM的UTF-8。

我在我的页面上使用多种语言(甚至西里尔字母)很长一段时间,当文件保存时没有BOM,我重新打开它们用编辑器编辑(cherouvim也指出),一些字符被损坏了。

请注意,当您尝试以UTF-8编码保存新创建的文件时,Windows的经典记事本会自动保存带有BOM的文件。

我个人保存带有BOM的服务器端脚本文件(.asp, .ini, .aspx)和没有BOM的.html文件。