zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    2016年3月3日
    性能测试之我解
    Vim命令合集
    vi-vim常用命令
    架构的本质是
    网站三层架构学习之一 分层式结构
    Spring 4 + Quartz 2.2.1 Scheduler Integration Example
    “城市民族工作条例”详解--建议废止
    字符串匹配处理
    LogBack简易教程
  • 原文地址:https://www.cnblogs.com/duanxz/p/2805004.html
Copyright © 2011-2022 走看看