Bootstrap

string 与 byte[] 的相互转化

 1、String 到 byte[]
String str = new String("hello world");
byte[] by = str.getBytes();

2、byte[] 到String
String str = new String("hello world");
byte[] by = str.getBytes();
String s = new String(by);还可以设置offset,在读取文件的二进制流时候特别有用,需要把二进制流直接变为String,可以这样:

StringBuffer strBf = new StringBuffer("");
InputStream stream = file.getInputStream(); //把文件读入
byte[] buffer = new byte[8192];
  while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1)
  {
           strBf.append(new String(buffer,0,bytesRead));//生成字符串
  }

;