Read both text and binary data from InputStream

I am trying to read data from a binary stream, parts of which should be parsed as UTF-8.

Using InputStreamdirectly for binary data and InputStreamReaderon top of it for UTF-8 text does not work, as the reader will read further and ruin the subsequent binary data, even if it is told to read the maximum of ncharacters.

I understand that this question is very similar to Reading from InputStream in several formats , but the proposed solution is specific to HTTP streams, which does not help me.

I thought to just read everything as binary data and subsequently convert the corresponding fragments to text. But I only have the length of the given characters in characters, not in bytes. So I need a thing that reads characters from a stream in order to know about the encoding.

Is there a way to tell InputStreamReader not to read further than it takes to read a given number of characters? Or is there a reader that supports both binary data and encoded text and can switch between these modes on the fly?

+5
source share
2 answers

First you need to read the binary parts. Where you recognize the part of the bytes that requires UTF-8 decoding, you need to extract these bytes and decode it.

DataInputStream dis = 
// read a binary type.
int num = dis.readInt();
int len = dis.readUnsignedShort();
// read a UTF-8 portion.
byte[] bytes = new byte[len];
dis.readFully(bytes);
String text = new String(bytes, "UTF-8");
// read some binary
double d = dis.readDouble();
+2
source

, StreamReader. , .

. , .. String.

, (, ProtocolRecord.) Serializable. . 2 :

(1) - java. DataInputStream DataOutputStream , / . , .

(2) readObject() writeObject() . DataInputStream DataOutputStream, . , .

, DataInputStream - , .

+2

All Articles