本文转自:http://blog.csdn.net/chenzhanhai/article/details/6367842
部分摘自http://hi.baidu.com/liu_ufo/blog/item/af0a330976df35ae2fddd4b4.html
首先,byte[]是字节数组类型,和int[]类似,只是一个是字节型的,一个是整型的;
char是UNICOEDE字符,为16位的整数;
String是个类,一般用来表示字符串的;
hello.getBytes()意思就是把hello这个字符串转化为字节流(byte型);一般前面加个byte[]型的变量,就是把转化后的字节流放到这个变量里,如下:
byte[] bt=hello.getBytes();
// char转byte
private byte[] getBytes (char[] chars) {
Charset cs = Charset.forName ("UTF-8");
CharBuffer cb = CharBuffer.allocate (chars.length);
cb.put (chars);
cb.flip ();
ByteBuffer bb = cs.encode (cb);
return bb.array();
}
// byte转char
private char[] getChars (byte[] bytes) {
Charset cs = Charset.forName ("UTF-8");
ByteBuffer bb = ByteBuffer.allocate (bytes.length);
bb.put (bytes);
bb.flip ();
CharBuffer cb = cs.decode (bb);
return cb.array();
}