In Java Base64 Decode, Base64 is an encoding scheme in a binary-to-text format that denotes binary data, which is in the form of printable ASCII string format by translating into radix 64 depictions. These Base64 data can be encoded or decoded based on the user’s requirements and can be done with the help of certain methods. For that, importing java.util.Base64 package is an essential step. The main advantage of encoding and decoding these data is its privacy as well as security. In the following sections, a detailed description of each method will be addressed.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Declaration:
Below is the declaration for Base64 decode:
public static class Base64.Decoder extends Object
How does Base64 Decode Work in Java?
Now, let us see the working of the Base64 decode.
- First, create an encoder object and encode the string/ bytes/ bytebuffer based on the requirement. It can be done using the method Base64.getEncoder().
- Once it is done, create a new array for the encoded data.
- To decode the data, create a decoder object, and create another array for storing decoded data.
- Decode the encoded data using the method decode().
- Print the result available in the decoder array.
Methods of Java Base64 decode
Following are the different methods of Java Base64 decode.
1. public byte[] decode ( byte[] arr )
- Decodes each and every byte from the input array with the help of the Base64 encoding scheme.
- Results will be written into a newly allocated byte array.
- The byte array returned will be having a length similar to the resulting bytes.
- Here, arr is the input byte array that has to be decoded.
- An IllegalArgumentException will be thrown if the input byte array is not in a valid format of Base64.
Example:
Code:
import java.util.Base64; public class Base64DecodeExample { public static void main(String[] args) { // encoder Base64.Encoder enc = Base64.getEncoder(); // Encode byte array byte arr[] = {'a'}; byte arr2[] = enc.encode(arr); System.out.println("Array encoded is: "+ arr2); // decoder Base64.Decoder dec = Base64.getDecoder(); // Decode byte array String ds = new String(dec.decode(arr2)); System.out.println("Array decoded is:"+ds); } }
Output:
An encoded and decoded result of an array gets printed on executing the code.
2. public byte[] decode ( Stringstr )
- Input string which is in the Base64 format, will be decoded with the help of the Base64 encoding scheme.
- Results will be written into a newly allocated byte array.
- Execution of this method will create an effect of executing the method decode( src.getBytes ( StandardCharsets.ISO_8859_1 ) ).
- Here, str is the input string that has to be decoded.
- An IllegalArgumentException will be thrown if the input string is not in a valid format of Base64.
Example:
Code:
import java.util.Base64; public class Base64DecodeExample { public static void main(String[] args) { // encoder Base64.Encoder enc = Base64.getEncoder(); String s = enc.encodeToString("EduCBA".getBytes()); System.out.println("String encoded is: "+ s); // decoder Base64.Decoder dec = Base64.getDecoder(); // Decode string String ds = new String(dec.decode(s)); System.out.println("String decoded is:"+ds); }}
Output:
An encoded and decoded result of a string gets printed on executing the code.
3. public int decode ( byte[] arr, byte[] arr2)
- Decodes each and every byte from the input array with the help of the Base64 encoding scheme.
- Results will be written into a byte array arr2 that starts the offset from 0.
- Here, arr is the input byte array that has to be decoded, and arr2 is the output array. Make sure that arr2 has enough space to accommodate the decoded input bytes.
- An IllegalArgumentException will be thrown if the input byte array is not in a valid format of Base64 or arr2 do not have enough space for writing the decoded input bytes.
Example:
Code:
import java.util.Base64; public class Base64DecodeExample { public static void main(String[] args) { // encoder Base64.Encoder enc = Base64.getEncoder(); byte arr[] = {'1'}; byte arr2[] = enc.encode(arr); byte arr3[] = new byte[5]; System.out.println("Array encoded is: "+ arr2); // decoder Base64.Decoder dec = Base64.getDecoder(); System.out.println("Array decoded is:"+ dec.decode(arr2,arr3)); }}
Output:
An encoded and decoded result of a byte array gets printed on executing the code.
4. public ByteBufferdecode ( ByteBufferbuff )
- Decodes each and every byte from the input byte buffer with the help of the Base64 encoding scheme.
- Results will be written into a newly allocated bytebuffer.
- Here, the buff is the inputbytebuffer that has to be decoded.
- An IllegalArgumentException will be thrown if the input bytebufferis not in a valid format of Base64.
Example:
Code:
import java.nio.ByteBuffer; import java.util.Base64; public class Base64DecodeExample { public static void main(String[] args) { // encoder Base64.Encoder enc = Base64.getEncoder(); String st = "Happy weekend"; ByteBuffer buff= ByteBuffer.wrap(st.getBytes()); ByteBuffer buff2 = enc.encode(buff); System.out.print("Encoded: "); while(buff2.hasRemaining()){ char ch = (char) buff2.get(); System.out.print(ch); } buff2.clear(); // decoder Base64.Decoder dec = Base64.getDecoder(); ByteBuffer buff3 = dec.decode(buff2); System.out.print(" Decoded: "); while(buff3.hasRemaining()){ char ch3 = (char) buff3.get(); System.out.print(ch3); } buff2.clear(); } }
Output:
An encoded and decoded result of a bytebuffergets printed on executing the code.
5. public InputStreamwrap ( InputStreaminpt )
- An input stream will be returned in order to decode the byte stream, which is Base64 encoded.
- Here, input is the input stream.
Example
Code:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Base64; public class Base64DecodeExample { public static void main(String[] args) throws IOException { try (InputStream inpt = new FileInputStream("F:\\EduCBA\\April\\Edu.txt")) { Base64.Encoder enc = Base64.getEncoder(); OutputStream opst = enc.wrap(new FileOutputStream("F:\\EduCBA\\April\\Eduout.txt")); int b1; while ((b1 = inpt.read()) != -1) { opst.write(b1); } opst.close(); } catch (IOException ie) { System.err.printf("I/O exception", ie.getMessage()); } try (FileOutputStream fopst = new FileOutputStream("F:\\EduCBA\\April\\Eduou.txt")) { Base64.Decoder dec = Base64.getDecoder(); InputStream inpt2 = dec.wrap(new FileInputStream("F:\\EduCBA\\April\\Eduout.txt")); int b1; while ((b1 = inpt2.read()) != -1) fopst.write(b1); inpt2.close(); } catch (IOException ie) { System.err.printf("I/O exception", ie.getMessage()); } } }
Output:
In this program, create three create text files, Edu, Eduout, Eduou, in a location for storing data, encoded data, and decoded data respectively. The below figure is the input data.
The encoded and decoded data will be written into the two other files on executing the code, as shown below.
The above is the detailed content of Java Base64 Decode. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
