1

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?

2
  • what's the type of pipedinputstream? Commented May 14, 2012 at 9:28
  • @Shine: make an educated guess :-) Commented May 14, 2012 at 9:31

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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()); 

Comments

0
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.

Comments

-1

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.

3 Comments

i want data to flow thru the pipedinputstream! it takes only byte[] as argument...
@VineetMenon So wrap InputStreamReader and OutputStreamWriter around them, then you can write chars. But my next question would be why you think you need pipes? I've never put a piped stream into production in 15 years.
:I want to exchange data(text) between 2 threads...synch. Anyways the problem is solved by Vivien's Solution..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.