Categories: Uncategorised

Java MalformedInputException: Input length = 1

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();
  }

 }

}
mahendravarman.m@gmail.com

Recent Posts

Spring Webflux Functional Endpoint – File Upload

In this blog using the Spring WebFlux module, we are going to leverage the functional…

10 months ago

Serverless Functions with Spring Cloud Function, AWS Lambda

Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…

10 months ago

Spring Boot + RabbitMQ – Decoupling Microservices Communication

RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…

10 months ago

Spring Integration – Sending files over SFTP

Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…

11 months ago

Spring Cloud Config Client

The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…

11 months ago

Handling CSV in Python

In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…

11 months ago