简体   繁体   中英

How to use the method of DataInputStream to read data writed by DataOutputStream.writeBytes(String)?

How to use the method of DataInputStream to read data writed by DataOutputStream.writeBytes(String)?

I really have no idea of this problem!

writeBytes(String) does not include any indication of the length written so unless you have output the length earlier there is no way to know how much to read.

Also note that writeBytes(String) only writes the bottom eight bits of each character in the string discarding the high bits - this may not be what you want.

If you want to write out a String look at writeUTF which does include the string length and can be read with DataInputStream.readUTF .

You can construct your DataOutputStream with an ByteArrayOutputStream and your DataInputStream with an ByteArrayInputStream using as buffer the byte array from ByteArrayOutputStream , for instance:

ByteArrayOutputStream inMemory = new ByteArrayOutputStream ();
DataOutputStream out = new DataOutputStream (inMemory);

DataInputStream in = new DataInputStream (new ByteArrayInputStream  (inMemory.toByteArray()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM