Video in progress

Strong Middle 📁 IO and NIO

A file name uploaded from macOS doesn't `equals` the name in the database, even though they look the same on screen. What is the cause, and how do you fix it?

Unicode can write one letter in two ways: a precomposed character (NFC) or a base letter + a combining mark (NFD). macOS, and archives created there, often give file names in NFD. Before comparing, you bring both to one form with Normalizer.normalize(s, Normalizer.Form.NFC).

📖 Answer

The letter ü can be of two kinds: U+00FC (a single character) or u + U+0308 (combining diaeresis). They look the same on screen, but they are different strings for Java:

String nfc = "ümit";          // "ümit": 4 characters
String nfd = "ümit";         // also "ümit" on screen, but 5 characters
nfc.equals(nfd);                   // false
Normalizer.normalize(nfd, Normalizer.Form.NFC).equals(nfc); // true

Turkish and German names, é, the Cyrillic short i (й or и + ̆): all of them have two forms like this. As a result: a unique index accepts the "same" name twice, search doesn't find it, and the file name doesn't match the database record.

Where it comes from: the old HFS+ file system forcibly converted names to NFD. APFS stores a name as it was given, but many macOS tools and zip archives created there still bring NFD names. Text typed on a keyboard is usually NFC.

The fix is to normalize at the boundary:

String safeName(String original) {
    return Normalizer.normalize(original.strip(), Normalizer.Form.NFC);
}

The rule: every name and identifier that comes from outside (a file name, a login, a search term) should be brought to NFC before storing and comparing. Then only one form lives in the database.

This is different from the Uzbek ʻ problem: oʻ and o' are different characters, and Normalizer doesn't merge them; for that you need a separate replacement rule.