zoukankan      html  css  js  c++  java
  • Java Base64编码解码实现

    我尝试过两种方式:java自带的sun.misc的工具类,还有commons-codec.jar

    1、sun.misc的工具类

    1         String encoderStr = null;
    2         BASE64Encoder encoder = new BASE64Encoder();
    3         try {
    4             encoderStr = encoder.encode(str.getBytes(DEFAULT_CHARSET));
    5         } catch (UnsupportedEncodingException e) {
    6             log.error("字符串【" + str + "】base64编码失败", e);
    7         }

    但测试的结果发现,需要自行对 和 做replaceAll替换为“”,得到的str才是正确的。

    2、commons-codec.jar

      这个第三方开源jar包也提供了对文件的编码和解码,简单也很好用,建议

     1 String strBase64 = base64.encodeToString(tempStrBase64.toString().getBytes(DEFAULT_CHARSET)); 

      其他用法,请参考api:

        http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

      对比较小的文件编码、解码:

    1 byte[] source = ...; // load your data here
    2 
    3 byte[] encoded = Base64.encode(source);
    4 
    5 byte[] decoded = Base64.decode(encoded);

      对比较大的文件编码、解码:

     1 InputStream inputStream = new FileInputStream("source.jpg");
     2 
     3 OutputStream outputStream = new FileOutputStream("encoded.b64");
     4 
     5 Base64.encode(inputStream, outputStream);
     6 
     7 outputStream.close();
     8 
     9 inputStream.close();
    10 
    11 代码示例Base64解码:
    12 
    13 InputStream inputStream = new FileInputStream("encoded.b64");
    14 
    15 OutputStream outputStream = new FileOutputStream("decoded.jpg");
    16 
    17 Base64.decode(inputStream, outputStream);
    18 
    19 outputStream.close();
    20 
    21 inputStream.close();
  • 相关阅读:
    表数据驱动之直接访问
    Sam format
    samtools faidx
    bwa index|amb|ann|bwt|pac|sa
    68.26-95.44-99.74 rule|empirical rule
    z-scores|zα
    Normally Distributed|
    数理统计与概率论的关系
    The General Addition Rule|complementation rule|special addition rule|
    Events|sample space|mutually exclusive events
  • 原文地址:https://www.cnblogs.com/yingsong/p/5625914.html
Copyright © 2011-2022 走看看