Home  >  Article  >  Java  >  How does Java implement Base64 encoding and decoding? Implement 4 methods of Base64 encoding and decoding

How does Java implement Base64 encoding and decoding? Implement 4 methods of Base64 encoding and decoding

青灯夜游
青灯夜游forward
2018-10-25 16:56:174091browse

The content of this article is to introduce how to implement Base64 encoding and decoding in Java? Implement 4 methods of Base64 encoding and decoding. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Why use Base64 encoding

Data is transmitted over the network using ascii. For some pictures, videos and other data, it may be encoded into the invisible part of ASCII. Different routing devices in the network process them differently, and this part of the data may be lost. In order to ensure the correctness of data transmission, Base64 encoding can be used to encode these invisible data into visible data.

Several ways to implement Base64 encoding and decoding in Java

Method 1

Use the BASE64Encoder and BASE64Decoder classes in the sun.misc package for encoding and decoding. This method is relatively old and is not recommended.

The code is as follows:

  /**
   * sun.misc方式Base64编码
   * @param str
   * @return
   */
  public static String encodeBySunMisc(String str) {    
     try {      
         return new BASE64Encoder().encode(str.getBytes("UTF-8"));
    } 
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();      
      return "";
    }
  }  
  /**
   * sun.misc方式Base64解码
   * @param str
   * @return
   */
  public static String decodeBySunMisc(String str) {    
     try {      
         byte[] result = new BASE64Decoder().decodeBuffer(str);      
         return new String(result);
    } 
    catch (IOException e) {
      e.printStackTrace();     
      return "";
    }
  }

Although the Base64 tool of sun.misc is in the jdk, it does not belong to the standard library, so it cannot be used directly in Eclipse. It can be used through manual introduction.

Solution:

Right-click the project->Properties->Java Build Path->Libraries, click Add External Jars, select %JAVA_HOME%\jre\lib\rt.jar. Can.

Method 2

Use Apache’s commons-code package. This method is slightly faster than the sun.misc method.

The code is as follows

  /**
   * commons-code方式Base64编码
   * @param str
   * @return
   */
  public static String encodeByCommonsCode(String str) {    
      byte[] result;    
      try {
      result = org.apache.commons.codec.binary.Base64.encodeBase64(str.getBytes("UTF-8"));      
      return new String(result);
    } 
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();      
      return "";
    }
  }  
  /**
   * commons-code方式Base64解码
   * @param str
   * @return
   */
  public static String decodeByCommonsCode(String str) {    
      byte[] result = org.apache.commons.codec.binary.Base64.decodeBase64(str.getBytes());    
      return new String(result);
  }

Using commons-code requires introducing dependencies. Taking the gradle project as an example, you need to add the following lines to build.gradle:

implementation 'commons-codec:commons-codec:1.11'

Method 3

Use Apache’s xerces tool. This tool is mainly used to parse xml and has Base64 encoding and decoding functions.

The code is as follows:

  /**
   * xerces方式Base64解码
   * @param str
   * @return
   */
  public static String decodeByXerces(String str) {    
     try {      
         byte[] result = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(str);      
         return new String(result);
    } 
    catch (Exception e) {
      e.printStackTrace();      return "";
    }
  }  
  /**
   * Java8中的Base64编码
   * @param str
   * @return
   */
  public static String encodeByJava8(String str) {    
      try {      
         return Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
    } 
    catch (Exception e) {
      e.printStackTrace();      
      return "";
    }
  }

Method 4

The util suite of Java8 already comes with Base64 encoding and decoding tools, and it is very efficient. It is recommended to use this way.

The code is as follows:

  /**
   * Java8中的Base64编码
   * @param str
   * @return
   */
  public static String encodeByJava8(String str) {    
      try {      
         return Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
    } 
    catch (Exception e) {
      e.printStackTrace();      
      return "";
    }
  }  
  /**
   * Java8中的Base64解码
   * @param str
   * @return
   */
  public static String decodeByJava8(String str) {    
       byte[] result = Base64.getDecoder().decode(str.getBytes());    
       return new String(result);
  }

Test several encoding effects:

The test code is as follows:

  private static void testEncodeAndDecode(String src) {
    String encedeStr1 = encodeBySunMisc(src);
    System.out.println("encode by sun misc: " + encedeStr1);
    
    String decedeStr1 = decodeBySunMisc(encedeStr1);
    System.out.println("decode by sun misc: " + decedeStr1);
    
    
    String encedeStr2 = encodeByCommonsCode(src);
    System.out.println("encode by commons-code: " + encedeStr2);
    
    String decedeStr2 = decodeByCommonsCode(encedeStr2);
    System.out.println("decode by commons-code: " + decedeStr2);

    
    String encedeStr3 = encodeByXerces(src);
    System.out.println("encode by xerces: " + encedeStr3);
    
    String decodeStr3 = decodeByXerces(encedeStr3);
    System.out.println("decode by xerces: " + decodeStr3);

    
    String encedeStr4 = encodeByJava8(src);
    System.out.println("encode by java8: " + encedeStr4);
    
    String decedeStr4 = decodeByJava8(encedeStr4);
    System.out.println("decode by java8: " + decedeStr4);
  }

The test results are as follows:

encode by sun misc: YWJjZGVmZ2hpamtsbW5vcHFyc3Q7
decode by sun misc: abcdefghijklmnopqrst;
encode by commons-code: YWJjZGVmZ2hpamtsbW5vcHFyc3Q7
decode by commons-code: abcdefghijklmnopqrst;
encode by xerces: YWJjZGVmZ2hpamtsbW5vcHFyc3Q7
decode by xerces: abcdefghijklmnopqrst;
encode by java8: YWJjZGVmZ2hpamtsbW5vcHFyc3Q7
decode by java8: abcdefghijklmnopqrst;

Compare the efficiency of several codecs. Use 20 characters for each encoding method to encode and then decode. It is executed 1 million times in total. Compare the total execution time.

The test code is as follows:

  // 测试sun.misc编解码效率
  private static void testSunMisc(String src) {    
     long begin = System.currentTimeMillis();    
     for(int i = 0; i < 1000000; i++) {
      String encedeStr1 = encodeBySunMisc(src + i);
      decodeBySunMisc(encedeStr1);
    }    long finish = System.currentTimeMillis();
    System.out.println("sun misc consume: " + (finish - begin) + "ms");
  }  
  // 测试commons-code编解码效率
  private static void testCommonsCode(String src) {    
     long begin = System.currentTimeMillis();    
     for(int i = 0; i < 1000000; i++) {
      String encedeStr1 = encodeByCommonsCode(src + i);
      decodeByCommonsCode(encedeStr1);
    }    long finish = System.currentTimeMillis();
    System.out.println("commons-code consume: " + (finish - begin) + "ms");
  }  
  // 测试xerces编解码效率
  private static void testXerces(String src) {    
      long begin = System.currentTimeMillis();    
      for(int i = 0; i < 1000000; i++) {
      String encedeStr1 = encodeByXerces(src + i);
      decodeByXerces(encedeStr1);
    }    long finish = System.currentTimeMillis();
    System.out.println("xerces consume: " + (finish - begin) + "ms");
  }  
  // 测试Java8编解码效率
  private static void testJava8(String src) {    
     long begin = System.currentTimeMillis();    
     for(int i = 0; i < 1000000; i++) {
      String encedeStr1 = encodeByJava8(src + i);
      decodeByJava8(encedeStr1);
    }    
    long finish = System.currentTimeMillis();
    System.out.println("java 8 consume: " + (finish - begin) + "ms");
  }
  public static void main(String[] args) {
    String src = "abcdefghijklmnopqrst;";

    testSunMisc(src);
    testCommonsCode(src);
    testXerces(src);
    testJava8(src);
  }

Tested 3 times in total, the output results are as follows:

commons-code consume: 3337ms
sun misc consume: 6532ms
xerces consume: 554ms
java 8 consume: 547ms

commons-code consume: 3148ms
sun misc consume: 6445ms
xerces consume: 498ms
java 8 consume: 466ms

commons-code consume: 3442ms
sun misc consume: 6674ms
xerces consume: 470ms
java 8 consume: 512ms

Conclusion

Old sun. The misc method is the least efficient, while the xerces and Java8 methods are the most efficient. Due to the convenience of Java8, it is recommended to directly use the Base64 tool that comes with Java8 for encoding and decoding.

The above is the detailed content of How does Java implement Base64 encoding and decoding? Implement 4 methods of Base64 encoding and decoding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete