Question
I have a byte[] loaded from a file, and I know that the file content is encoded as UTF-8.
In some debugging code, I need to convert that byte array into a String. Is there a one-line way to do this in Java?
For example, given something like this:
byte[] data = ...; // loaded from a UTF-8 file
how can I convert it into a String correctly?
I assume this should mainly involve creating a new String from the bytes using the UTF-8 character encoding.
Short Answer
By the end of this page, you will understand how to convert a UTF-8 byte[] into a Java String, why character encodings matter, which APIs to use, and what mistakes to avoid when working with text loaded from files or network data.
Concept
Text in memory and text in files are not always stored the same way.
A Java String stores characters, while a byte[] stores raw bytes. To turn bytes into readable text, Java must know which character encoding was used when those bytes were created.
If your byte array is UTF-8 encoded, you should decode it as UTF-8:
String text = new String(bytes, StandardCharsets.UTF_8);
This matters because the same byte values can mean different characters under different encodings. If you use the wrong encoding, the result may contain garbled text like é instead of é.
UTF-8 is the most common encoding for files, APIs, JSON, logs, and web content, so knowing how to decode UTF-8 correctly is a basic and important Java skill.
In Java, the most direct way to convert a UTF-8 byte[] to a String is to use a String constructor that accepts both the byte array and the charset.
String text = new String(bytes, StandardCharsets.UTF_8);
This is clear, safe, and avoids relying on the platform default encoding.
Mental Model
Think of a byte[] as a box of numbered codes and a String as the final readable message.
The encoding is the dictionary used to translate those numbers into characters.
byte[]= raw encoded data- UTF-8 = the translation dictionary
String= the decoded human-readable text
If you use the wrong dictionary, the message is decoded incorrectly. So the key idea is simple:
Bytes are not text until you decode them with the correct charset.
Syntax and Examples
The standard Java syntax is:
String text = new String(bytes, StandardCharsets.UTF_8);
You need this import:
import java.nio.charset.StandardCharsets;
Example
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
byte[] bytes = {72, 101, 108, 108, 111};
String text = new String(bytes, StandardCharsets.UTF_8);
System.out.println(text);
}
}
Output:
Hello
Example with non-ASCII characters
java.nio.charset.StandardCharsets;
{
{
[] bytes = .getBytes(StandardCharsets.UTF_8);
(bytes, StandardCharsets.UTF_8);
System.out.println(text);
}
}
Step by Step Execution
Consider this example:
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
byte[] bytes = "Hi".getBytes(StandardCharsets.UTF_8);
String text = new String(bytes, StandardCharsets.UTF_8);
System.out.println(text);
}
}
Step by step:
"Hi".getBytes(StandardCharsets.UTF_8)converts the stringHiinto UTF-8 bytes.- Those bytes are stored in
bytes. new String(bytes, StandardCharsets.UTF_8)tells Java to decode the byte array using UTF-8.- Java reads the bytes and converts them back into characters.
System.out.println(text)printsHi.
For simple ASCII text like Hi, UTF-8 uses one byte per character. For characters like é, UTF-8 may use multiple bytes, which is why the charset must be specified explicitly.
Real World Use Cases
Converting byte[] to String with UTF-8 is common in many real programs:
- Reading file contents: when a file is loaded as bytes and you want readable text
- HTTP responses: APIs often return UTF-8 encoded JSON or plain text
- Logging and debugging: inspect binary payloads that actually contain text
- Message queues: systems often send UTF-8 encoded messages as bytes
- Database exports/imports: text may be read from streams as raw bytes first
- Configuration files: YAML, JSON,
.properties, and text-based formats are often UTF-8
Example with a file:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
byte[] bytes = Files.readAllBytes(Path.of("data.txt"));
String text = new String(bytes, StandardCharsets.UTF_8);
Example with an API response body stored as bytes:
String json = new String(responseBytes, StandardCharsets.UTF_8);
Real Codebase Usage
In real projects, developers often use this conversion in small, focused places rather than everywhere.
Common patterns
- Debugging raw payloads
- Validation before parsing
- Reading text from files or streams
- Converting request/response bodies
- Guarding against null or empty data
Example with a guard clause
import java.nio.charset.StandardCharsets;
public String decodeBody(byte[] body) {
if (body == null || body.length == 0) {
return "";
}
return new String(body, StandardCharsets.UTF_8);
}
Example before JSON parsing
String json = new String(bytes, StandardCharsets.UTF_8);
if (!json.trim().startsWith("{")) {
throw new IllegalArgumentException("Expected JSON object");
}
Why StandardCharsets.UTF_8 is preferred
Common Mistakes
A few common mistakes cause confusing bugs.
1. Using the platform default encoding
Broken example:
String text = new String(bytes);
Why this is a problem:
- It uses the system default charset.
- The result may differ between machines.
- UTF-8 data can be decoded incorrectly on systems using a different default charset.
Use this instead:
String text = new String(bytes, StandardCharsets.UTF_8);
2. Encoding and decoding with different charsets
Broken example:
byte[] bytes = "café".getBytes(StandardCharsets.UTF_8);
String text = new String(bytes, java.nio.charset.StandardCharsets.ISO_8859_1);
System.out.println(text);
This produces incorrect text because the bytes were encoded as UTF-8 but decoded as ISO-8859-1.
3. Assuming bytes are always text
Not every byte[] represents text. Some byte arrays are:
Comparisons
Here is a quick comparison of common approaches:
| Approach | Example | Good choice? | Notes |
|---|---|---|---|
| Explicit UTF-8 decoding | new String(bytes, StandardCharsets.UTF_8) | Yes | Best general choice for known UTF-8 data |
| Charset name as string | new String(bytes, "UTF-8") | Usually | Works, but less modern and less convenient |
| Default charset | new String(bytes) | No | Depends on machine settings |
| Read text directly from file API | Files.readString(path, StandardCharsets.UTF_8) | Yes | Best if you are reading from a file and do not need raw bytes |
byte[] vs
Cheat Sheet
import java.nio.charset.StandardCharsets;
String text = new String(bytes, StandardCharsets.UTF_8);
Rules
- Use the correct charset when converting bytes to text.
- If the bytes are UTF-8, decode with
StandardCharsets.UTF_8. - Avoid
new String(bytes)unless you intentionally want the default charset. - Prefer
StandardCharsets.UTF_8over the string literal"UTF-8".
Common file shortcut
String text = java.nio.file.Files.readString(path, StandardCharsets.UTF_8);
Common reverse operation
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Warning signs
- Text looks like
éinstead ofé - Output changes across systems
- Replacement character
�appears
FAQ
How do I convert a UTF-8 byte[] to a String in Java?
Use:
String text = new String(bytes, StandardCharsets.UTF_8);
Why should I not use new String(bytes)?
Because it uses the platform default charset, which may not be UTF-8 on every machine.
Is "UTF-8" the same as StandardCharsets.UTF_8?
They refer to the same encoding, but StandardCharsets.UTF_8 is usually preferred because it is safer and cleaner.
What happens if I use the wrong encoding?
The text may become corrupted or display strange characters such as ñ, é, or �.
Is converting bytes to a string always safe?
Only if the bytes actually represent text in the encoding you specify. Binary data should not be treated as text.
Can I read a UTF-8 file directly as a string instead of reading bytes first?
Yes. In many cases this is simpler:
Mini Project
Description
Build a small Java utility that reads UTF-8 encoded bytes and prints the decoded text. This mirrors a common debugging task: inspecting file or network data that arrives as a byte[] but actually contains text.
Goal
Create a program that converts UTF-8 byte arrays into readable Java strings and demonstrates the result with sample inputs.
Requirements
- Create a
byte[]from a sample UTF-8 string. - Convert the byte array back into a
Stringusing UTF-8. - Print both the byte length and the decoded text.
- Include at least one sample containing a non-ASCII character.
- Avoid using the platform default charset.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Array Initialization Syntaxes Explained
Learn all common C# array initialization syntaxes with examples, rules, comparisons, and mistakes beginners often make.