Base64 Encoding and Decoding Example In Java 7

Base64 encoding is useful for translating binary data to ASCII string format.  This is very commonly used in transferring binary files such as images or or PDF file to another application using XML.  In this tutorial you will learn how you can achieve this using Java 7 library.  You will also learn how to decode a encoded string so that original binary data can be retrieved.

Here  is the Code snippet for the code in the video -


package org.nilendu;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
 
import javax.xml.bind.DatatypeConverter;
 
public class Base64Example {
 
 public static void main(String args[]) throws IOException{
   String inputFile = "c:/workspace/samplepdffile.pdf";
   byte[] fileInBytes = loadFile(inputFile);
   String fileInBase64 = DatatypeConverter.printBase64Binary(fileInBytes);
   System.out.println(fileInBase64);
 
   byte[] decodedFile = DatatypeConverter.parseBase64Binary(fileInBase64);
   FileOutputStream fileOutputStream = new FileOutputStream("C:/workspace/newPdfSample.pdf");
   fileOutputStream.write(decodedFile);
   fileOutputStream.flush();
   fileOutputStream.close(); 
 }
 
 public static byte[] loadFile(String sourcePath) throws IOException
 {
   InputStream inputStream = null;
   try {
      inputStream = new FileInputStream(sourcePath);
      return readFully(inputStream);
   } finally {
       if (inputStream != null) {
         inputStream.close();
       }
    }
 }
 
public static byte[] readFully(InputStream stream) throws IOException {
   byte[] buffer = new byte[8192];
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
   int bytesRead;
   while ((bytesRead = stream.read(buffer)) != -1) {
     baos.write(buffer, 0, bytesRead);
   }
    return baos.toByteArray();
 }
 
}

What is Polymorphism

Polymorphism is one of the four principles of Object Oriented Programming.  Polymorphism allows programs to flow in different ways depending on the situation or conditions.  In this video tutorial I have explained what is polymorphism and few simple examples.