开发者

reading from DataInputStream without knowing the output type

开发者 https://www.devze.com 2023-03-03 22:41 出处:网络
Say i\'开发者_运维百科m using DataInputStream to recieve data, but I don\'t know if I should use (for example) readUTF, readInt or readLong. Is there a method that tells me what type of data is writte

Say i'开发者_运维百科m using DataInputStream to recieve data, but I don't know if I should use (for example) readUTF, readInt or readLong. Is there a method that tells me what type of data is written on the other side?


No, there's no mechanism to introspect the stream to find out this information. If you need to do this, then the sender needs to add meta-data to the stream indicating what sort of data is coming next.

For example, the sender can send a 0 byte (which could be a signal for "the next data item is an int"), and then send the int, then send a 1 byte (the signal for "the next data item is a long"), followed by the long itself.

The consumer would read off the signals, and know whether to call readInt or readLong.

Alternatively, you can use ObjectInput and ObjectOutput instead of DataInputStream, which performs the introspection for you (if you use writeObject() and readObject()).


No. It is all a raw binary data for it. Unless you specify what you expect, it is all the same for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号