1. 程式人生 > >string 與 byte[] 的相互轉化

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));//生成字串
  }