As part of this blog lets go through when this exception occurs and how to fix it.
When any of the methods of java.nio.file.Files class is used to read the file contents it assumes the file is encoded using UTF-8. If file is encoded in different format and when we try to read the file using methods which assumes file is encoded in UTF-8 we will get this MalformedInputException. To fix this we will have to use methods which takes Charset as param and pass the actual encoding Charset.
To demo this have created a file and saved the file using encoding UTF-16 LE.
Pasted below the code for reading the file content as streams using Files.lines method.
public class ReadFileAsStream {
private static String fileName = "D:\\samplefile.txt";
public static void main(String args[]) {
Path path = Paths.get(fileName);
Stream<String> contents = null;
try {
contents = Files.lines(path);
contents.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} finally {
contents.close();
}
}
}
Presented below the implementation of Files.lines method where we could see the UTF_8 Charset is used for decoding the file which results in java.nio.charset.MalformedInputException.
public static Stream<String> lines(Path path) throws IOException {
return lines(path, UTF_8.INSTANCE);
}
As a fix use Files.lines method which takes the Charset used for decoding as param.
public class ReadFileAsStream {
private static String fileName = "D:\\samplefile.txt";
public static void main(String args[]) {
Path path = Paths.get(fileName);
Stream<String> contents = null;
try {
contents = Files.lines(path, StandardCharsets.UTF_16LE);
contents.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} finally {
contents.close();
}
}
}
In this blog using the Spring WebFlux module, we are going to leverage the functional…
Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…
RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…
Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…
The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…
In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…