I tried this so far:
public String readchar (Reader input) throws java.io.IOException
{
int i16 = input.read(); // UTF-16 as int
if (i16 == -1) return null;
char c16 = (char)i16; // UTF-16
if (Character.isHighSurrogate(c16)) {
int low_i16 = input.read(); // low surrogate UTF-16 as int
if (low_i16 == -1)
throw new java.io.IOException ("Can not read low surrogate");
char low_c16 = (char)low_i16;
int codepoint = Character.toCodePoint(c16, low_c16);
return new String (Character.toChars(codepoint));
}
else
return Character.toString(c16);
}
But it contains unsafe casts. I have no idea how to avoid them. Is it possible?
int
tochar
will never crash, and because of yourint
s coming frominput.read();
you won't lose any information by the cast. \$\endgroup\$int
does not fit intochar
. \$\endgroup\$