CodeGym /Courses /Kotlin SELF /BOM — how to recognize it and why it breaks a file

BOM — how to recognize it and why it breaks a file

Kotlin SELF
Level 44, Lesson 3
Available

1. BOM: what it is and why it exists

If you have ever seen the situation “the string looks the same, but == says ‘no’”, then congratulations: you have encountered a class of problems caused by invisible characters. BOM (Byte Order Mark) is one of the most popular “ninjas” in this category. It can appear at the beginning of a text file and not reveal itself during normal viewing, and then suddenly break your parsing, headers, and comparisons.

BOM is a service marker: a set of special bytes at the very beginning of a file that was historically used to hint “which encoding” and/or “which byte order” (this especially applies to UTF‑16). Important: BOM is not user data; it is not “part of the text” that a person wanted to save. But if you naively read the file as a string and then compare the “first word”, BOM becomes sand in the gears.

Imagine you expect a passport ("HEADER") as input, but you are handed a passport with an invisible sticker over the first letter. Visually it is the same document, but formally it is not.

How BOM breaks the beginning of a file

In practice, BOM most often shows up like this: the first line or the first token “doesn’t match”, even though in logs or in the editor everything looks identical. This is especially painful for formats like “the first line is a header” or “the file starts with a magic signature”.

Let’s imagine our training CLI project: a task list that is saved to a text file. We agreed that the first line of the file must be a header:

TODO_V1

And then the task lines follow (the format is not important right now—it’s just text).

fun main() {
    val expectedHeader = "TODO_V1"
    val actualHeader = "\uFEFFTODO_V1"

    println(expectedHeader == actualHeader) // false
}

From a human point of view, it is “the same thing”. From a program’s point of view, it is not, because \uFEFF at the beginning makes the string different.

And then you write an honest check:

fun isValidHeader(header: String): Boolean {
    return header == "TODO_V1"
}

…and it starts returning false “for no reason”. There is a reason. It is just invisible—like bugs in production.

How to detect BOM by bytes

When it comes to BOM, it is very useful to remember the boundary: on disk there are bytes, and the string appears later. If we want to confidently recognize BOM, it is logical to first look at the first bytes of the file. For UTF‑8, the classic BOM prefix is three bytes:

EF BB BF

To check this in Kotlin, we need a ByteArray. It’s like IntArray, but for bytes: an array of primitives, without “wrappers”. Kotlin explicitly separates such arrays into distinct types (including ByteArray).

Mini-check for a UTF‑8 BOM by the first three bytes:

fun hasUtf8Bom(bytes: ByteArray): Boolean {
    return bytes.size >= 3 &&
        bytes[0] == 0xEF.toByte() &&
        bytes[1] == 0xBB.toByte() &&
        bytes[2] == 0xBF.toByte()
}

Note two practical points.

First, we must check bytes.size >= 3. BOM may not exist, the file may be empty, the file may be two bytes long—and if you forget the check, you will get an exception like “index out of bounds”, and the culprit will not be BOM at all, but your haste.

Second, we compare with toByte(), because the literals 0xEF are Int, while the array contains Byte. Kotlin forces you to be honest here: if you want to compare, convert types explicitly.

How BOM looks in a string: '\uFEFF'

Sometimes you don’t want to dig into bytes. For example, you have already read the file via readText(Charsets.UTF_8) and got a string, and then somewhere later header parsing unexpectedly breaks. In such cases, BOM may show up as the first character of the string '\uFEFF'.

It is important to understand: this is not “some kind of space”. And it is not trim()’s job to remove BOM. trim() works with whitespace characters and line breaks, but BOM is a separate entity, and the behavior can easily be not what you were hoping for.

Check “is there a BOM character at the start of the string”:

fun startsWithBomChar(text: String): Boolean {
    return text.isNotEmpty() && text[0] == '\uFEFF'
}

And careful removal:

fun dropLeadingBomChar(text: String): String {
    return if (text.isNotEmpty() && text[0] == '\uFEFF') {
        text.substring(1)
    } else {
        text
    }
}

The key word here is careful. We don’t “always cut off the first character”; we do it only if we have confidently recognized the BOM character.

What BOMs exist: the minimum for practice

Right now, it’s more important for us not to memorize Unicode “by heart”, but to build practical intuition: BOM is a prefix that can have different lengths. We will focus on the most common case (UTF‑8), but it is useful to know that UTF‑16 also likes to start a file with service bytes.

Encoding (common cases) BOM in hex (at the start of the file) Length
UTF‑8
EF BB BF
3 bytes
UTF‑16 LE / BE variants exist (often 2 bytes) 2 bytes

Why am I not listing all UTF‑16 variants in detail? Because the goal of this lecture is to learn to recognize the very fact of a BOM and its effect, not to run an exam called “guess the endianness”. It’s enough for us to know: “for UTF‑8 it’s 3 bytes EF BB BF, and other encodings may also have service bytes.” This already saves a lot of time during debugging.

How to remove BOM correctly: check first

Here comes a moment where a beginner often makes a “sharp and elegant” move and then spends a week chasing ghosts: “let’s always drop the first 3 bytes!”—and the “BOM problem will disappear”.

Yes, it will disappear. Along with the first three bytes of real data in files where there was no BOM. That is, you will fix one scenario and break ten others, just quieter ones.

The correct idea: check first, then remove.

Removing a UTF‑8 BOM at the byte level:

fun dropUtf8Bom(bytes: ByteArray): ByteArray {
    return if (hasUtf8Bom(bytes)) {
        bytes.copyOfRange(3, bytes.size)
    } else {
        bytes
    }
}

ByteArray is that very “primitive array” of bytes, which is convenient for such operations.

Embedding BOM checking into a task project

Now let’s put everything together into a mini story, as close to real life as possible. Suppose our file data/todo.txt must start with the header TODO_V1. We read the first line and compare.

For simplicity, let’s make a function that takes the first line from the text:

fun firstLine(text: String): String {
    val idx = text.indexOf('\n')
    return if (idx == -1) text else text.substring(0, idx)
}

Now we read the file in UTF‑8 (as agreed in the previous lecture—we explicitly specify the encoding) and validate the header:

import java.io.File

fun main() {
    val text = File("data/todo.txt").readText(Charsets.UTF_8)
    val header = firstLine(text)

    println("header='$header'") // may start with BOM
    println(header == "TODO_V1") // false, if header = "\uFEFFTODO_V1"
}

The problem here is that readText(Charsets.UTF_8) honestly read the file as UTF‑8, but if an editor or utility added a BOM, it turns into a character in the string, and you get an “invisible prefix”.

A “string-level” fix looks like this: clean the header from the BOM character before comparing.

import java.io.File

fun main() {
    val text = File("data/todo.txt").readText(Charsets.UTF_8)
    val header = dropLeadingBomChar(firstLine(text))

    println(header == "TODO_V1") // true
}

This is much better than “always cut it off”, because we remove it conditionally.

Diagnostics: how to prove it is BOM

When you suspect a BOM, you really want to “see proof”. Here we have two good techniques: look at the first bytes, or print the code of the first character of the string. Both options are useful, because sometimes you read the file in a different way and the symptom changes.

First, let’s print the first 6 bytes in hex form (a minimal variant, without complex formatters):

fun firstBytesHex(bytes: ByteArray, n: Int): String {
    val count = minOf(n, bytes.size)
    return bytes.take(count).joinToString(" ") { b ->
        "%02X".format(b.toInt() and 0xFF)
    }
}

And now apply it:

import java.io.File

fun main() {
    val bytes = File("data/todo.txt").readBytes()
    println(firstBytesHex(bytes, 6)) // for example: EF BB BF 54 4F 44
}

If you see EF BB BF, it is almost certainly a UTF‑8 BOM, and then come the bytes 54 4F 44 (that is ASCII/UTF‑8 for T O D).

If you are already reading a string and want to check the BOM character:

fun main() {
    val s = "\uFEFFTODO_V1"
    println(s[0].code) // 65279
}

The number 65279 is the code for U+FEFF. That is the same “invisible passenger”.

BOM breaks more than just your code

Sometimes it feels like: “Well, I’m parsing it wrong.” But BOM can break tools too. For example, Kotlin changelogs mentioned issues with UTF‑8 BOM in Kotlin scripting (meaning it’s not only you suffering; grown-ups with compilers suffer too).

This is useful to remember for two reasons. First, you stop feeling like the only person on the planet who “broke a string”. Second, you start treating BOM as a real external factor that must be considered when working with files, especially if files can come from different editors, OSes, and tools.

2. Typical mistakes when working with BOM

Mistake #1: “let’s cut off the first character (or the first 3 bytes) every time—and done”.
This is very tempting because it looks like a quick fix. But this way you start damaging correct files without a BOM. The worst part is that the damage may not be noticeable immediately: the header “got fixed”, but the first task or the first letter of the first line disappeared. You should remove the BOM only after verifying that it is actually present.

Mistake #2: mixing up levels: “bytes vs string”.
A common approach is: the file has already been read as a String, but then they try to “check the first bytes”—and start building weird constructs that compare a Char with 0xEF. These are different things. If you want to reliably check a UTF‑8 BOM as EF BB BF, do it on a ByteArray. If you want to quickly clean the “invisible character” at the start of a string, check '\uFEFF'. The important thing is simply not to mix these levels in one check.

Mistake #3: expecting trim() to remove BOM.
trim() is not a “universal mop for all invisible problems”. It is not designed to remove BOM, and even if it accidentally helped in some environment, that is not a contract you should rely on. For BOM, it is better to have an explicit check for '\uFEFF' or a first-bytes check.

Mistake #4: no byte-array length check.
Checking BOM by bytes almost always starts with bytes.size >= 3 (for a UTF‑8 BOM). If you forget this condition, on an empty file or a short file you will crash on an index. And it will be especially annoying because the crash will happen “during diagnostics”, not in your actual logic.

Mistake #5: trying to fix BOM by “picking a different encoding”.
Sometimes people try: “let’s read UTF‑16… let’s read ASCII…”. This may turn the text into gibberish, but the BOM will not disappear as a phenomenon. BOM is a separate layer of the problem: a service prefix in the file. Encoding matters, but BOM must either be correctly handled at input, or removed as a service marker, rather than trying to “guess” the encoding until it looks pretty.

1
Task
Kotlin SELF, level 44, lesson 3
Locked
Clean header
Clean header
1
Task
Kotlin SELF, level 44, lesson 3
Locked
Ghost character
Ghost character
1
Task
Kotlin SELF, level 44, lesson 3
Locked
Signal in bytes
Signal in bytes
1
Task
Kotlin SELF, level 44, lesson 3
Locked
Hex check
Hex check
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION