Blob、InputStream、byte[]、String互转

1、InputStream转byte[]

private byte[] InputStreamToByte(InputStream is) throws IOException {
   ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
   int ch;
   while ((ch = is.read()) != -1) {
    bytestream.write(ch);
   }
   byte imgdata[] = bytestream.toByteArray();
   bytestream.close();
   return imgdata;
  }


2、Blob转byte[]

从数据库中读取Blob类型数据后,要转换成String类型,即转换成InputStream,再从InputStream转成byte[],再到String即可。如下:

//把数据库中blob类型转换成String类型

public String convertBlobToString(Blob blob){
  
  String result = "";
  try {
   ByteArrayInputStream msgContent =(ByteArrayInputStream) blob.getBinaryStream();
   byte[] byte_data = new byte[msgContent.available()];
   msgContent.read(byte_data, 0,byte_data.length);
   result = new String(byte_data);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return result;
 }

3、byte[]转InputStream

byte[] data;   
InputStream is = new ByteArrayInputStream(data); 

4、byte[]转String

String a = new String(byte,"utf-8");
或者
String b = new String(byte);

5、String转byte[]

String a = "abcdefg";
byte[] b = a.getBytes();
原文地址:https://www.cnblogs.com/duanxz/p/2805004.html