简体   繁体   中英

String and byte[] issue java

I am converting a String to byte[] and then again byte[] to String in java using the getbytes() and String constructor,

String message = "Hello World";
byte[] message1 = message.getbytes();

using PipedInput/OutputStream I send this to another thread, where,

byte[] getit = new byte[1000];
pipedinputstream.read(getit);
print(new String(getit));

This last print result in 1000 to be printed... I want the actual string length. How can i do that?

When reading the String, you need to get the number of bytes read, and give the length to your String:

byte[] getit = new byte[1000];
int readed = pipedinputstream.read(getit);
print(new String(getit, 0, readed));

Note that if your String is longer than 1000 bytes, it will be truncated.

You are ignoring the number of bytes read. Do it as below:

  byte[] getit = new byte[1000]; 
  int bytesRead = pipedinputstream.read(getit); 
  print(new String(getit, 0, bytesRead).length()); 
public String getText (byte[] arr)
{
StringBuilder sb = new StringBuilder (arr.length);

for (byte b: arr)
    if (b != 32)
        sb.append ((char) b);

return sb.toString ();
}

not so clean, but should work.

I am converting a String to byte[] and then again byte[] to String

Why? The round trip is guaranteed not to work. String is not a container for binary data. Don't do this. Stop beating your head against the wall: the pain will stop after a while.

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