Video in progress

What is a charset, and why should you specify it explicitly when reading a file?

A charset is the rule for turning bytes into characters (UTF-8, windows-1251, ISO-8859-1). If one charset is used when writing and another when reading, the text turns into garbage. Specifying it explicitly means the code doesn't depend on which machine it runs on.

📖 Answer

A single word in Cyrillic is one set of bytes in UTF-8 and completely different bytes in windows-1251. A file does not say which encoding it was written in; the reader has to know.

// explicit and reliable
String s = Files.readString(path, StandardCharsets.UTF_8);
byte[] b = "o'zbek".getBytes(StandardCharsets.UTF_8);

Before Java 18, if you gave no charset, the OS default was used: usually UTF-8 on Linux, often windows-1252 or 1251 on Windows. The result: everything is fine on the developer's machine, but Cyrillic letters break on the server. Since Java 18 the default is UTF-8 (JEP 400), but for older versions and external systems it is still better to write it explicitly.

Use the StandardCharsets constants: if you write the "UTF-8" string and misspell the name, you get UnsupportedEncodingException.