Java8 BASE64 Codec

Source: Internet
Author: User
Tags base64 encode string alphanumeric characters

Java8 BASE64 Codec


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:

Encode string asB64 = Base64.getencoder (). Encodetostring ("some string". GetBytes ("Utf-8")); System.out.println (asB64); The output is: c29tzsbzdhjpbmc=//decoding byte[] asbytes = Base64.getdecoder (). Decode ("c29tzsbzdhjpbmc="); System.out.println (New String (Asbytes, "utf-8")); Output is: 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:

String basicencoded = Base64.getencoder (). encodetostring ("Subjects?abcd". GetBytes ("Utf-8")); System.out.println ("Using Basic Alphabet:" + basicencoded); String urlencoded = Base64.geturlencoder (). encodetostring ("Subjects?abcd". GetBytes ("Utf-8")); System.out.println ("Using URL Alphabet:" + urlencoded);//output is: Using Basic alphabet:c3viamvjdhm/ywjjza==using URL Alphab et: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:

stringbuilder sb = new  StringBuilder ();for  (int t = 0; t < 10; ++t)  {   Sb.append (Uuid.randomuuid (). toString ());} Byte[] toencode = sb.tostring (). GetBytes ("Utf-8"); String mimeencoded = base64.getmimeencoder (). encodetostring (Toencode); System.out.println (mimeencoded);//  output is: Ndu5ztfkndetmdvlny00mdfiltk3yjgtmwrlmmrkmwezmzc5ytjkzmezy2ytm2y2my00y2q4ltk5zmytmtu1nzy0mwm5zjk4oda5zjvjogutogmxni00zmvjl Tgyzjctnmvjytu5mtaxzwuynjq1mjjjndmtyza0mc00mjexltk0nwmtymfizgrlndk5otzhmdmxzge5ztytzwvhys00ogfmltlhmjgtmdm1zjayy2qxnduyow Zimji3ndctnmi3oc00yjgylthizgqtm2myy2e3zgnjymixotq1mdvkogqtmzizyi00mdg0lwe0zmityzkwmgeznduxztiwotllztjiyjctmwi3ms00ymqzltg Yyjutzgrmymyxnda4mjg3ytmxzjmxzmmtytdmyy00yzmyltkynzktztc2zdc5zwu4n2m5zdu1nmq4nwytmdkwoc00yjiylwiwywitmzjiymzmm2m0otbm 

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 buffering buffer 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, both without buffering buffer:

Public void wrapping ()  throws IOException {  String src =  " This is the content of any resource read from somewhere " +      " into a stream. this can be text, image,  video or any other stream. ";   //  Encoder Package outputstream,  file/tmp/buff-base64.txt content is BASE64 encoded form   try  ( Outputstream os = base64.getencoder (). Wrap (Newfileoutputstream ("/tmp/buff-base64.txt"))  {     os.write (Src.getbytes ("Utf-8"));  }  //  decoder encapsulates InputStream,   and streaming decoding,  without buffering   // is being consumed. There is no  Need to buffer the content of the file just for decoding  it.  try  (Inputstream is = base64.getdecoder () Wrap (NEWFIleinputstream ("/tmp/buff-base64.txt"))  {    int len;     byte[] bytes = new byte[100];    while  ((Len = is.read ( bytes)  != -1)  {      system.out.print (new String (bytes,  0, len,  "Utf-8"));     }  }}


Java8 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.