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

	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *