Blob、InputStream、byte[]、String互转

本文介绍了如何在Java中实现不同数据类型的转换,包括InputStream到byte[], Blob到String, byte[]到InputStream, byte[]到String, 以及String到byte[]的具体实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值