为什么 DataInputStream 不能正确读取 char?
Why DataInputStream can't read char correctly?
我尝试在 DataInputStream 中写入字符串,当从 DataInputStream 读取单个字符时,我遇到了错误。
我预计 readChar()
return 'q',但是方法:
assertEquals('q', DataInputStream("q".byteInputStream(Charsets.UTF_8)).readChar())
抛出异常:
java.io.EOFException
at java.io.DataInputStream.readChar(DataInputStream.java:365)
请查看 DataInput.readChar()
,其中指出:
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
.
最后一句基本上也是解决方案。如果您使用 writeChar
写入数据,读取会按预期工作,即以下将为您提供一个成功的测试用例:
assertEquals('q', DataInputStream(ByteArrayOutputStream().apply {
DataOutputStream(this).use {
it.writeChars("q")
}
}.toByteArray().inputStream())
.readChar())
以下,即使界面中未提及,也可能有效:
assertEquals('q', DataInputStream("q".byteInputStream(Charsets.UTF_16BE)).readChar())
我尝试在 DataInputStream 中写入字符串,当从 DataInputStream 读取单个字符时,我遇到了错误。
我预计 readChar()
return 'q',但是方法:
assertEquals('q', DataInputStream("q".byteInputStream(Charsets.UTF_8)).readChar())
抛出异常:
java.io.EOFException at java.io.DataInputStream.readChar(DataInputStream.java:365)
请查看 DataInput.readChar()
,其中指出:
Reads two input bytes and returns a char value. Let
a
be the first byte read andb
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 interfaceDataOutput
.
最后一句基本上也是解决方案。如果您使用 writeChar
写入数据,读取会按预期工作,即以下将为您提供一个成功的测试用例:
assertEquals('q', DataInputStream(ByteArrayOutputStream().apply {
DataOutputStream(this).use {
it.writeChars("q")
}
}.toByteArray().inputStream())
.readChar())
以下,即使界面中未提及,也可能有效:
assertEquals('q', DataInputStream("q".byteInputStream(Charsets.UTF_16BE)).readChar())