Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8286287

Reading file as UTF-16 causes Error which "shouldn't happen"

XMLWordPrintable

    • b07
    • 17
    • b23
    • generic
    • generic
    • Verified

        A DESCRIPTION OF THE PROBLEM :
        If a text file is UTF-8 and has an odd number of characters, trying to read it as UTF-16 throws an Error caused by MalformedInputException:

        Files.readString(Paths.get("text.txt"), StandardCharsets.UTF_16);

        A comment in the java.lang.String method which causes the Error says "// Substitution is always enabled, // so this shouldn't happen". Clearly the intent is that only the MalformedInputException should be thrown.

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        Create a UTF-8 file text.txt containing an odd number of characters. Create, compile and run Test.java with the provided source code.

        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        Exception caught, no output.
        ACTUAL -
        Exception in thread "main" java.lang.Error: java.nio.charset.MalformedInputException: Input length = 1
                at java.base/java.lang.String.decodeWithDecoder(String.java:1220)
                at java.base/java.lang.String.newStringNoRepl1(String.java:796)
                at java.base/java.lang.String.newStringNoRepl(String.java:748)
                at java.base/java.lang.System$2.newStringNoRepl(System.java:2439)
                at java.base/java.nio.file.Files.readString(Files.java:3370)
                at Test.main(Test.java:8)
        Caused by: java.nio.charset.MalformedInputException: Input length = 1
                at java.base/java.nio.charset.CoderResult.throwException(CoderResult.java:274)
                at java.base/java.lang.String.decodeWithDecoder(String.java:1213)
                ... 5 more

        ---------- BEGIN SOURCE ----------
        import java.nio.charset.StandardCharsets;
        import java.nio.file.Files;
        import java.nio.file.Paths;

        public class Test {
            public static void main(String[] args) {
                try {
                    Files.readString(Paths.get("text.txt"), StandardCharsets.UTF_16);
                } catch (Exception e) {}
            }
        }
        ---------- END SOURCE ----------

        FREQUENCY : always


          1. Test.java
            0.3 kB
          2. test.txt
            0.0 kB

              naoto Naoto Sato
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              8 Start watching this issue

                Created:
                Updated:
                Resolved: