Stringpublic String(byte[] bytes, String charsetName) throws UnsupportedEncodingException Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required. Parameters:bytes - the bytes to be decoded into characters charsetName - the name of a supported charsetThrows:UnsupportedEncodingException - If the named charset is not supported NullPointerException - If charsetName is null
to GuoYangHai(Start):byte[] a; String ls_s=new String(a);用这种方法建立的String有和byte[]一样的长度,但是byte[] a = (ByteBuffer)buf.array(); String ls = new String(a);这样得到的byte[]后面有很多无效的字符,怎样才能建立一个与byte中有效字符一样长的String呢?
String竟然没提供valueOf(byte[],index,count)的方法,真是过份,我现在一程序从unix接收一定格式的数据,第几位到第几位是什么都有规定,因为String没有这个方法,只好不断地写new String(byte[] bytes, int offset, int length) ,new肯定是很没效率的吧,还没想到折衷的办法。
String charsetName)
throws UnsupportedEncodingException
Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.
Parameters:bytes - the bytes to be decoded into characters
charsetName - the name of a supported charsetThrows:UnsupportedEncodingException - If the named charset is not supported
NullPointerException - If charsetName is null
String ls_s=new String(a);用这种方法建立的String有和byte[]一样的长度,但是byte[] a = (ByteBuffer)buf.array();
String ls = new String(a);这样得到的byte[]后面有很多无效的字符,怎样才能建立一个与byte中有效字符一样长的String呢?
byte[] bytes = null;
//..........
bytes = buf.array();
StringBuffer strbuf = new StringBuffer();int i = 0;
while(bytes[i] != 0){
strbuf .append((char)bytes[i++]);
}String string = new String(ab);