Why This Happens
MalformedInputException occurs when reading text with the wrong character encoding. For example, reading a UTF-8 file as ISO-8859-1 may work but reading an ISO-8859-1 file as UTF-8 will fail because some byte sequences are invalid UTF-8.
The Problem
// File is encoded in ISO-8859-1 but read as UTF-8
String content = Files.readString(Path.of("data.txt")); // Defaults to UTF-8The Fix
// Specify the correct charset
String content = Files.readString(Path.of("data.txt"), StandardCharsets.ISO_8859_1);
// Or handle errors gracefully:
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE);Step-by-Step Fix
- 1
Identify the encoding
Determine the actual encoding of the file. Check for BOM markers, file metadata, or the source system's documentation.
- 2
Specify the correct charset
Pass the correct Charset to file reading methods instead of relying on the default.
- 3
Handle encoding errors
Use CodingErrorAction.REPLACE to substitute invalid characters, or CodingErrorAction.IGNORE to skip them.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free