因为UTF-8文件中的BOM而破坏工具是我经验中很常见的事情。我不知道为什么那里有如此多的downvote(但是这让我有机会尝试获得足够的投票赢得一个特殊的SO徽章);
更重要的是:UTF-8 BOM通常没有什么意义,但它完全有效(尽管不鼓励)规格。现在的问题是很多人都不知道BOM在UTF-8中有效,因此编写了不能正确处理这些文件的破坏的工具/ API。
现在您可能会遇到两个不同的问题:您可能希望从Java处理该文件,或者您需要使用Java以编程方式创建/修复其他(破碎)工具所需的文件。
我曾经在一次咨询会中发现,帮助台将不断收到用户发出的问题的文本编辑器的问题,这些文本编辑器会产生完全有效的Java生成的UTF-8文件。所以我必须解决这个问题,确保从我们处理的每一个UTF-8文件中删除BOM。
我想从文件中删除BOM,您可以创建一个新文件,并跳过前三个字节。例如:
... $ file /tmp/src.txt
/tmp/src.txt: UTF-8 Unicode (with BOM) English text
... $ ls -l /tmp/src.txt
-rw-rw-r-- 1 tact tact 1733 2012-03-16 14:29 /tmp/src.txt
... $ hexdump -C /tmp/src.txt | head -n 1
00000000 ef bb bf 50 6f 6b 65 ...
您可以看到,文件以“ef bb bf”开头,这是(完全有效的)UTF-8 BOM。
这是一种通过跳过前三个字节来获取文件并复制该文件的方法:
public static void workAroundbrokenToolsAndAPIs(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
source.position(3);
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom( source, 0, source.size() - 3 );
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
请注意,这是“原始”:您通常希望首先确定您在调用此消息之前拥有BOM或“可能发生不良想法”[TM]。
你可以看看你的文件:
... $ file /tmp/dst.txt
/tmp/dst.txt: UTF-8 Unicode English text
... $ ls -l /tmp/dst.txt
-rw-rw-r-- 1 tact tact 1730 2012-03-16 14:41 /tmp/dst.txt
... $ hexdump -C /tmp/dst.txt
00000000 50 6f 6b 65 ...
BOM已经走了
private static InputStream checkForUtf8BOMAndDiscardIfAny(InputStream inputStream) throws IOException {
PushbackInputStream pushbackInputStream = new PushbackInputStream(new BufferedInputStream(inputStream), 3);
byte[] bom = new byte[3];
if (pushbackInputStream.read(bom) != -1) {
if (!(bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF)) {
pushbackInputStream.unread(bom);
}
}
return pushbackInputStream; }
请注意,这是有效的,但肯定不会修复更严重的问题,您可以在工作链中的其他工具不能正常工作与具有BOM的UTF-8文件。
这里有一个更完整答案的问题的链接,涵盖其他编码: