[英]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, 我正在使用getbytes()
和String构造函数将Java中的String转换为byte [],然后再次将byte []转换为String,
String message = "Hello World";
byte[] message1 = message.getbytes();
using PipedInput/OutputStream I send this to another thread, where, 使用PipedInput / OutputStream我将此发送到另一个线程,
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. 最后的打印结果是要打印1000条...我想要实际的字符串长度。 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: 读取String时,您需要获取读取的字节数,并为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. 请注意,如果您的字符串长于1000个字节,它将被截断。
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 我将一个String转换为byte [],然后再将byte []转换为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. 停止将头撞在墙上:一段时间后疼痛会停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.