8219196: DataOutputStream.writeUTF may throw unexpected exceptions

Brian Burkhalter brian.burkhalter at oracle.com
Fri Mar 15 19:59:51 UTC 2019


So like this:

    static int writeUTF(String str, DataOutput out) throws IOException {
        int strlen = str.length();

        // use charAt instead of copying String to char array
        int utflen = 0;
        for (int i = 0; i < strlen && utflen < 65536; i++) {
            int c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                utflen++;
            } else if (c > 0x07FF) {
                utflen += 3;
            } else {
                utflen += 2;
            }
        }

        if (utflen > 65535)
            throw new UTFDataFormatException("encoded string too long");

> On Mar 15, 2019, at 12:54 PM, Martin Buchholz <martinrb at google.com> wrote:
> 
> Another idea: simply move the existing utflen > 65535 into the loop.
> With modern processors, that should be close to free.



More information about the core-libs-dev mailing list