Tuesday, 6 March 2018

Base64 encoding and decoding in Java

In this post, you are going to learn below things.
a.   What is Base64 Encoding/decoding
b.   How to encode data in Base64
c.   Where can I use Base64 encoding
d.   How much more memory base-64 require to represent the data?
e.   How can I perform base64 encoding in Java?

What is Base64 encoding/decoding?
Base64 is one of binary-to-text encoding scheme. In binary-to-text encoding, we encode binary data in plain text.

Below tables summarizes all the symbols in base64 scheme.

Value
Char
Value
Char
Value
Char
Value
Char
0
A
16
Q
32
g
48
w
1
B
17
R
33
h
49
x
2
C
18
S
34
i
50
y
3
D
19
T
35
j
51
z
4
E
20
U
36
k
52
0
5
F
21
V
37
l
53
1
6
G
22
W
38
m
54
2
7
H
23
X
39
n
55
3
8
I
24
Y
40
o
56
4
9
J
25
Z
41
p
57
5
10
K
26
a
42
q
58
6
11
L
27
b
43
r
59
7
12
M
28
c
44
s
60
8
13
N
29
d
45
t
61
9
14
O
30
e
46
u
62
+
15
P
31
f
47
v
63
/

Output Padding
Each base-64 encoded digit is represented by 6 bits. When data is not split exactly by 6 bits, then padding needs to be done. Data can be padded by ‘==’ (or) =.

The final '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes.

How to encode data in Base-64?
Let me explain with an example, how the string "java" is represented in Base64 encoding scheme.

"java" represented in ASCII form like below.
01101010011000010111011001100001

Since base64 encoding scheme requires 6 bits to represent a character, divide the above binary information into 6 bits groups from left to right.

011010   100110   000101   110110   011000   01
   26          38           5           54          24
   a            m            F           2            Y

As you see, above example, last group data is not split exactly by 6 bits. We end up with 2 bits. To make it 6 bits, we need to pad 4 0's at end.

011010   100110   000101   110110    011000   010000
   26          38           5           54           24          16
   a            m            F           2             Y            Q
  
Since last group contain only one byte (01, before adding 0000), we need to pad the encoded information with '=='.

So final encoded value is amF2YQ==.

Where can I use Base64 encoding?
It is used, when you want to transfer some binary information over network and network is not supporting transfer of binary information, you can encode the binary data using Base-64 and transfer over the network.

How much more memory base-64 require to represent the data?
Base-64 maps 3 bytes (8 x 3 = 24 bits) in 4 Base-64 characters (6 x 4 = 24 bits). Therefore it requires 4/3 = 1.3333333 times the original. So Base64 encoding uses 33% more storage.

How can I perform base64 encoding in Java?
'java.util.Base64' class provides functionality to encode and decode the information.

How to get Base64 Encoder?
Encoder encoder = Base64.getEncoder();

How to get Base64 Decoder?
Decoder decoder = Base64.getDecoder();

Find the below working application.
Test.java
package com.sample.test;

import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;

public class Test {
 public static void main(String args[]) {
  Encoder encoder = Base64.getEncoder();
  Decoder decoder = Base64.getDecoder();

  String originalData = "java";
  byte[] encodedBytes = encoder.encode(originalData.getBytes());
  String encodedStr = new String(encodedBytes);

  byte[] decodedBytes = decoder.decode(encodedBytes);
  String decodedStr = new String(decodedBytes);

  System.out.println("Original Data is : " + originalData);
  System.out.println("Encoded Data is : " + encodedStr);
  System.out.println("Decoded data is : " + decodedStr);

 }
}

Output
Original Data is : java
Encoded Data is : amF2YQ==
Decoded data is : java




Hamcrest: array: Match every element of array with specific matcher

By using 'array' matcher, you can create a matcher that matches array whose elements are satisfied by the specified matchers.

For ex
Integer[] primes = { 2, 3, 5, 7 };
assertThat("Checking first 4 primes", primes, array(equalTo(2), equalTo(3), equalTo(5), equalTo(7)));

Make sure that the number of matchers are equal to number of elements in the array.

Find the below working applicaiton.

TestApp.java

package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.array;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Test;

public class TestApp {

 @SuppressWarnings("unchecked")
 @Test
 public void testmethod() {
  String[] empIds = { "I312", "I768", "I456" };
  assertThat("Checking empIds details", empIds, array(equalTo("I312"), equalTo("I768"), equalTo("I456")));

  Integer[] primes = { 2, 3, 5, 7 };
  assertThat("Checking first 4 primes", primes, array(equalTo(2), equalTo(3), equalTo(5), equalTo(7)));

 }
}




Previous                                                 Next                                                 Home

Monday, 5 March 2018

How to write multiple input streams to a file

In this post, I am going to show you how to read the data from multiple input streams and write to a file. Let me explain an example with plain java code and later I am going to show you how can we simplify the same code using SequenceInputStream class provided by Java.

Below snippet reads the data from multiple input streams and write to the file.

byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;

try (OutputStream outputStream = new FileOutputStream(file)) {
         for (InputStream inputStream : inputStreams) {
                  if (inputStream == null) {
                           continue;
                  }
                  while ((bytesRead = inputStream.read(buffer)) != -1) {
                           outputStream.write(buffer, 0, bytesRead);
                  }
         }

}

Find the below working application.

FileUtil.java
package com.sample.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 /**
  * Reads the data from multiple input streams and write to the file.
  * 
  * @param file
  * @param inputStreams
  * @throws IOException
  * @throws FileNotFoundException
  */
 public static void writeToFile(File file, InputStream... inputStreams) throws FileNotFoundException, IOException {
  if (file == null) {
   throw new IllegalArgumentException("file should not be null");
  }

  if (inputStreams == null) {
   throw new IllegalArgumentException("inputStreams can't be null");
  }

  byte[] buffer = new byte[BUFFER_SIZE];
  int noOfBytesRead;

  try (OutputStream outputStream = new FileOutputStream(file)) {
   for (InputStream inputStream : inputStreams) {
    if (inputStream == null) {
     continue;
    }
    while ((noOfBytesRead = inputStream.read(buffer)) != -1) {
     outputStream.write(buffer, 0, noOfBytesRead);
    }
   }

  } finally {
   for (InputStream inputStream : inputStreams) {
    if (inputStream == null) {
     continue;
    }

    inputStream.close();
   }
  }
 }

 public static void writeToFile(String filePath, InputStream... inputStreams)
   throws FileNotFoundException, IOException {
  writeToFile(new File(filePath), inputStreams);
 }
}

Test.java
package com.sample.test;

import java.io.FileInputStream;
import java.io.InputStream;

import com.sample.util.FileUtil;

public class Test {
 public static void main(String args[]) throws Exception {
  String destinationPath = "C:\\Users\\krishna\\dest.log";
  
  String logFile1 = "C:\\Users\\krishna\\app1.log";
  String logFile2 = "C:\\Users\\krishna\\app2.log";
  String logFile3 = "C:\\Users\\krishna\\app3.log";
  
  InputStream inputStream1 = new FileInputStream(logFile1);
  InputStream inputStream2 = new FileInputStream(logFile2);
  InputStream inputStream3 = new FileInputStream(logFile3);
  
  FileUtil.writeToFile(destinationPath, inputStream1, inputStream2, inputStream3);
  
 }
}

Java provides 'SequenceInputStream' class, this is used to process collection of input stream in one shot.

'SequenceInputStream' provides below constructors.
SequenceInputStream(Enumeration<? extends InputStream> e)
SequenceInputStream(InputStream s1, InputStream s2)

Step 1: Create a SequenceInputStream from enumeration of input streams
InputStream inputStream1 = new FileInputStream(logFile1);
InputStream inputStream2 = new FileInputStream(logFile2);
InputStream inputStream3 = new FileInputStream(logFile3);

List<InputStream> inputStreams = Arrays.asList(inputStream1, inputStream2, inputStream3);

Enumeration<InputStream> e = Collections.enumeration(inputStreams);

Step 2: Now write the content to the file using SequenceInputStream.

try (OutputStream outputStream = new FileOutputStream(file)) {
         while ((noOfBytesRead = sequenceInputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, noOfBytesRead);
         }
}

Find the below working example.


FileUtil.java
package com.sample.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.SequenceInputStream;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 /**
  * Reads the data from multiple input streams and write to the file.
  * 
  * @param file
  * @param inputStreams
  * @throws IOException
  * @throws FileNotFoundException
  */
 public static void writeToFile(File file, SequenceInputStream sequenceInputStream)
   throws FileNotFoundException, IOException {
  if (file == null) {
   throw new IllegalArgumentException("file should not be null");
  }

  if (sequenceInputStream == null) {
   throw new IllegalArgumentException("sequenceInputStream can't be null");
  }

  byte[] buffer = new byte[BUFFER_SIZE];
  int noOfBytesRead;

  try (OutputStream outputStream = new FileOutputStream(file)) {
   while ((noOfBytesRead = sequenceInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, noOfBytesRead);
   }
  } finally {
   sequenceInputStream.close();
  }
 }

 public static void writeToFile(String filePath, SequenceInputStream sequenceInputStream)
   throws FileNotFoundException, IOException {
  writeToFile(new File(filePath), sequenceInputStream);
 }
}

Test.java
package com.sample.test;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import com.sample.util.FileUtil;

public class Test {
 public static void main(String args[]) throws Exception {
  String destinationPath = "C:\\Users\\krishna\\dest.log";

  String logFile1 = "C:\\Users\\krishna\\app1.log";
  String logFile2 = "C:\\Users\\krishna\\app2.log";
  String logFile3 = "C:\\Users\\krishna\\app3.log";

  InputStream inputStream1 = new FileInputStream(logFile1);
  InputStream inputStream2 = new FileInputStream(logFile2);
  InputStream inputStream3 = new FileInputStream(logFile3);

  List<InputStream> inputStreams = Arrays.asList(inputStream1, inputStream2, inputStream3);

  Enumeration<InputStream> e = Collections.enumeration(inputStreams);
  SequenceInputStream sequenceInputStream = new SequenceInputStream(e);

  FileUtil.writeToFile(destinationPath, sequenceInputStream);

 }
}

Hamcrest: Matchers to work with arrays

Hamcrest library provides below methods to work with arrays.


Previous                                                 Next                                                 Home