kotlineofexception

Why DataInputStream can't read char correctly?


I tried to write String in DataInputStream, when read from DataInputStream single char, but I have an error.

I expected, that readChar() return 'q', but method:

assertEquals('q', DataInputStream("q".byteInputStream(Charsets.UTF_8)).readChar())

Throws exception:

java.io.EOFException at java.io.DataInputStream.readChar(DataInputStream.java:365)


Solution

  • Please have a look at DataInput.readChar() which states:

    Reads two input bytes and returns a char value. Let a be the first byte read and b be the second byte. The value returned is:

    (char)((a << 8) | (b & 0xff))
    

    This method is suitable for reading bytes written by the writeChar method of interface DataOutput.

    The last sentence is basically also the solution. If you write the data using writeChar, reading works as expected, i.e. the following will give you a succeeding test case:

    assertEquals('q', DataInputStream(ByteArrayOutputStream().apply {
                        DataOutputStream(this).use {
                          it.writeChars("q")
                        }
                      }.toByteArray().inputStream())
                      .readChar())
    

    The following, even though not mentioned in the interface, may also work out:

    assertEquals('q', DataInputStream("q".byteInputStream(Charsets.UTF_16BE)).readChar())