Java 8 implements BASE64 codec

Source: Internet
Author: User
Tags base64 alphanumeric characters

Java has always lacked the BASE64 encoding API, which is often used by third-party API implementations in project development. However, Java 8 implements the BASE64 codec API, which contains the Java.util package. I'm going to do an introduction to the Java 8 BASE64 API below.

The Java.util.Base64 tool class provides a set of static methods for obtaining the following three BASE64 codecs:

1) Basic code
2) URL encoding
3) MIME encoding

The basic encoding is a standard BASE64 encoding that is used to handle general requirements: The output does not add line breaks, and the output is composed of letters plus numbers. Here's how to use:

[Java]View Plaincopy print?
    1. //  encoding   
    2. String  asb64 = base64.getencoder (). encodetostring ( "some string". GetBytes ( Span class= "string", "Utf-8"));   
    3. system.out.println (asB64);  < span class= "comment" >//  output is:  c29tzsbzdhjpbmc=  
    4.    
    5. //  decode   
    6. byte[]  Asbytes = base64.getdecoder (). Decode (system.out.println (new string (asbytes, //  output:  some string  


Compared to early processing of BASE64 coding requirements, it is not likely to be simpler. Because no external dependencies are required: Commons-codec or Sun.misc.BASE64Decoder or JAXB datatypeconverter.

URL encoding is also a requirement that we often face, but because the URL has a special meaning to the backslash "/", the URL code needs to replace it and replace it with an underscore. For example, the following:

[Java]View Plaincopy print?
    1. string basicencoded = base64.getencoder (). Encodetostring ( "SUBJECTS?ABCD". GetBytes ( "Utf-8"));  
    2. System.out.println (
    3. &NBSP;&NBSP;&NBSP;
    4. string urlencoded  = base64.geturlencoder (). encodetostring ( "SUBJECTS?ABCD". GetBytes ( "Utf-8"));   
    5. system.out.println (
    6. //  output to:   
    7. USING&NBSP;BASIC&NBSP;ALPHABET:&NBSP;C3VIAMVJDHM/YWJJZA==&NBSP;&NBSP;
    8. using url alphabet: c3viamvjdhm_ywjjza==  


As the above example shows, if you are using a basic encoder, the output may contain a backslash "/" character, but if you use a URL encoder, the output is safe for the URL.

The MIME encoder generates BASE64 output using basic alphanumeric characters, and is friendly to MIME format: each line outputs no more than 76 character, and each line ends with a "\ r \ n" symbol. For example, the following:

[Java]View Plaincopy print?
  1. StringBuilder sb = new StringBuilder ();
  2. for (int t = 0; t < ++t) {
  3. Sb.append (Uuid.randomuuid (). toString ());
  4. }
  5. byte[] Toencode = sb.tostring (). GetBytes ("Utf-8");
  6. String mimeencoded = Base64.getmimeencoder (). encodetostring (Toencode);
  7. System.out.println (mimeencoded);
  8. The output is:
  9. Ndu5ztfkndetmdvlny00mdfiltk3yjgtmwrlmmrkmwezmzc5ytjkzmezy2ytm2y2my00y2q4ltk5
  10. Zmytmtu1nzy0mwm5zjk4oda5zjvjogutogmxni00zmvjltgyzjctnmvjytu5mtaxzwuynjq1mjjj
  11. Ndmtyza0mc00mjexltk0nwmtymfizgrlndk5otzhmdmxzge5ztytzwvhys00ogfmltlhmjgtmdm1
  12. Zjayy2qxnduyowzimji3ndctnmi3oc00yjgylthizgqtm2myy2e3zgnjymixotq1mdvkogqtmziz
  13. Yi00mdg0lwe0zmityzkwmgeznduxztiwotllztjiyjctmwi3ms00ymqzltgyyjutzgrmymyxnda4
  14. Mjg3ytmxzjmxzmmtytdmyy00yzmyltkynzktztc2zdc5zwu4n2m5zdu1nmq4nwytmdkwoc00yjiy
  15. Lwiwywitmzjiymzmm2m0otbm


The Java.util.Base64 class encapsulates all BASE64 encoders and decoders, and also supports the encapsulation of streams-a very elegant construct-including high coding and efficiency (no buffer buffers required)-that is, the input and output of encoders and decoders do not need buffer buffers. Here's an example of how the encoder encapsulates the FileOutputStream, and how the decoder encapsulates the FileInputStream, without buffering buffer:

[Java]View Plaincopy print?
    1. Public void Wrapping () throws IOException {
    2. String src = "The content of any resource read from somewhere" +
    3. "into a stream." This can is text, image, video or any other stream. ";
    4. //Encoder package OutputStream, file/tmp/buff-base64.txt content is BASE64 encoded form
    5. try (outputstream OS = Base64.getencoder (). Wrap (Newfileoutputstream ("/tmp/buff-base64.txt"))) {
    6. Os.write (Src.getbytes ("Utf-8"));
    7. }
    8. //Decoder package InputStream, as well as stream decoding, without buffering
    9. //is being consumed.  There is no need to buffer the content of the file just for decoding it.
    10. try (InputStream is = Base64.getdecoder (). Wrap (Newfileinputstream ("/tmp/buff-base64.txt"))) {
    11. int len;
    12. byte[] bytes = new byte[100];
    13. While (len = is.read (bytes))! =-1) {
    14. System.out.print (New String (bytes, 0, Len, "Utf-8"));
    15. }
    16. }
    17. }

Java 8 implements BASE64 codec

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.