2012-05-14 98 views
1

我将字符串转换为byte [],然后再次使用getbytes()和String构造的Java为String的byte [],字符串和字节[]问题的java

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

使用PipedInput/OutputStream中我发这个到另一个线程,其中,

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

这最后的打印结果1000打印...我想要的实际字符串长度。我怎样才能做到这一点?

+0

'pipedinputstream'的类型是什么? – Shine

+0

@Shine:做出一个有教养的猜测:-) –

回答

1

当读取字符串,你需要得到的字节数读取,并给予长度的字符串:

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

注意,如果你的字符串是超过1000个字节,它将被截断。

+0

ooh..ya ..我只是忘了那... thx ... –

1

您忽略了读取的字节数。做到这一点,如下:

byte[] getit = new byte[1000]; 
    int bytesRead = pipedinputstream.read(getit); 
    print(new String(getit, 0, bytesRead).length()); 
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(); 
} 

不那么干净,但应该工作。

-1

我将字符串转换为byte [],然后再次字节[]为String

为什么?往返旅程保证不起作用。字符串不是二进制数据的容器。不要这样做。不要将头撞在墙上:一段时间后疼痛会停止。

+0

我想要数据流通过pipedinputstream!它只需要字节[]作为参数... –

+0

@VineetMenon因此,围绕它们包装InputStreamReader和OutputStreamWriter,然后您可以编写字符。但是我的下一个问题就是为什么你认为你需要管道?我从未在15年内将管道流投入生产。 – EJP

+0

:我想在2个线程之间交换数据(文本)...同步。无论如何,这个问题由Vivien解决方案解决.. –