Sub topic 13
Encoding and Decoding Bytes
A Java String holds text. But files and network connections store or send data as bytes. A byte is a unit of data that can hold eight bits.
To move text between a String and bytes, Java needs rules for the conversion. Those rules are called a character encoding, or charset.
- Encoding turns text into bytes.
- Decoding turns bytes back into text.
This matters because different charsets can assign different meanings to the same bytes. If you encode with one charset and decode with another, the result may be wrong.
Choose a charset explicitly
UTF-8 is a widely used charset. It can represent Unicode text, including English letters, accented letters, and many other symbols. Unicode is a standard that assigns numbers to text characters.
UTF-8 uses one byte for many common English letters. Other characters can need two, three, or four bytes. So the number of bytes is not always the same as the length of a Java string.
Java provides StandardCharsets.UTF_8 to name UTF-8. Use it for both encoding and decoding when UTF-8 is the agreed format.
A round trip with UTF-8
A round trip means converting text to bytes and then decoding those bytes back into text. This example also shows what happens when you use a different charset to decode.
Save it as EncodeText.java:
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
class EncodeText {
public static void main(String[] args) {
String text = "caf\u00E9";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String decoded = new String(bytes, StandardCharsets.UTF_8);
String wrong = new String(bytes, StandardCharsets.ISO_8859_1);
System.out.println("String length: " + text.length());
System.out.println("Byte count: " + bytes.length);
System.out.println("Bytes: " + Arrays.toString(bytes));
System.out.println("UTF-8 matches: " + text.equals(decoded));
System.out.println("Other charset matches: " + text.equals(wrong));
}
}The text is café. The escape sequence \u00E9 represents é. Using the escape lets this example avoid depending on how your editor saves that character in the Java source file.
Run the program:
javac EncodeText.java
java EncodeTextThe output is:
String length: 4
Byte count: 5
Bytes: [99, 97, 102, -61, -87]
UTF-8 matches: true
Other charset matches: falseHere is what happened:
getBytes(StandardCharsets.UTF_8)encoded the string into a byte array. An array holds a fixed number of values.new String(bytes, StandardCharsets.UTF_8)decoded the array with the same charset.equalsconfirmed that the decoded text has the original contents.- Decoding the same bytes with
ISO_8859_1, another charset, produced different text.
The string has length four, but its UTF-8 encoding has five bytes. In this example, each of c, a, and f uses one byte. The é uses two.
Reading the byte values
Bytes are often shown in hexadecimal, a way of writing numbers using the digits 0 to 9 and the letters A to F. This table shows the UTF-8 bytes for the example:
| Text | UTF-8 bytes in hexadecimal |
|---|---|
| `c` | `63` |
| `a` | `61` |
| `f` | `66` |
| `é` | `C3 A9` |
Java displays the last two bytes as -61 and -87 in the array output. That is because Java's byte type displays values from -128 to 127. Those are the same bytes shown as C3 and A9 in the table.
Why matching matters
A decoder reads bytes according to its charset's rules. It does not automatically know which charset was used to create them.
For example, UTF-8 encodes é as the two bytes C3 A9. If a program reads those bytes as ISO-8859-1 instead, it interprets each byte under different rules. The result is not the original é.
The wrong charset does not always cause an error. A program may produce text that looks strange and continue running. This is sometimes called garbled text.
When you exchange text with another program, agree on the charset. If you control both sides, UTF-8 is often a good choice:
- The sender encodes the text as UTF-8.
- The sender passes the bytes to the receiver.
- The receiver decodes those bytes as UTF-8.
Matching charsets is necessary, but the bytes must also arrive unchanged.
Writing and reading a file
A file is a common place to store encoded text. The following program writes UTF-8 text to a temporary file and reads it back. A temporary file is a file created for short-term use.
This example uses Java 11 or later. Save it as TextFileRoundTrip.java:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
class TextFileRoundTrip {
public static void main(String[] args) throws IOException {
String text = "caf\u00E9";
Path file = Files.createTempFile("text-example-", ".txt");
try {
Files.writeString(file, text, StandardCharsets.UTF_8);
String readBack = Files.readString(file, StandardCharsets.UTF_8);
System.out.println("File text matches: " + text.equals(readBack));
} finally {
Files.deleteIfExists(file);
}
}
}Run it with:
javac TextFileRoundTrip.java
java TextFileRoundTripIt prints:
File text matches: trueA Path identifies a location in the file system. Files.writeString encodes and writes the text. Files.readString reads and decodes it. Both calls name UTF-8 explicitly.
The finally block deletes the temporary file after the attempt, even if reading or writing fails. IOException is a type of error that can occur when working with files.
Handle invalid bytes
Not every sequence of bytes is valid UTF-8. Bytes may be damaged, incomplete, or encoded in a different format.
When you use new String(bytes, StandardCharsets.UTF_8), Java replaces invalid input rather than reporting an error. The replacement character is usually shown as �. That can make text readable, but it can also hide lost information.
If you must reject invalid UTF-8, use a decoder configured to report errors. A decoder is an object that turns bytes into text.
Save this program as CheckUtf8.java:
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
class CheckUtf8 {
public static void main(String[] args) {
byte[] damaged = {(byte) 0xC3, 0x28};
String replaced = new String(damaged, StandardCharsets.UTF_8);
System.out.println("Replacement present: " + replaced.contains("\uFFFD"));
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
decoder.decode(ByteBuffer.wrap(damaged));
System.out.println("Valid UTF-8");
} catch (CharacterCodingException e) {
System.out.println("Invalid UTF-8");
}
}
}Run it with:
javac CheckUtf8.java
java CheckUtf8It prints:
Replacement present: true
Invalid UTF-8ByteBuffer.wrap makes the byte array available to the decoder. The try and catch blocks handle the error that the decoder reports.
A replacement character in text does not always prove an error occurred: it could have been part of the original text. Use a reporting decoder when you need to check whether input is valid UTF-8.
Encoding can also replace input that the chosen charset cannot represent. If losing text is unacceptable, use an encoder configured to report errors rather than replace the input.
Avoid common mistakes
- Leaving out the charset: Java offers methods that use a default charset. That default can depend on the Java version and configuration. Name the charset explicitly when reading or writing text.
- Treating all bytes as text: An image or other non-text file is not necessarily encoded text. Decoding arbitrary bytes as UTF-8 can damage the information.
- Using encoding as protection: Encoding is not encryption. Anyone who has the bytes and knows the charset can decode the text.
- Ignoring the other system: UTF-8 is useful only if the reader expects UTF-8 too.
Exercises
Exercise
You encode "café" as UTF-8. Why does the resulting array have five bytes rather than four?
Show answer
The letters c, a, and f each use one byte in UTF-8. The letter é uses two, for a total of five bytes.
Exercise
A program receives a byte array that must be valid UTF-8. Should it rely on new String(bytes, StandardCharsets.UTF_8) to report invalid bytes?
Show answer
No. That constructor replaces invalid input. Use a UTF-8 CharsetDecoder configured with CodingErrorAction.REPORT to reject it.