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();
  • 相关阅读:
    PAT1007
    PAT1005
    PAT1002
    PAT1003
    PAT1016
    PAT 1018
    PAT1009
    pat 1037
    解决Git合并分支发生的冲突
    站和队列的基本使用
  • 原文地址:https://www.cnblogs.com/duanxz/p/2805004.html
Copyright © 2011-2022 走看看