How to Encode and Decode a Message in Java

We are going to see how to encode and decode a message in Java in this tutorial. So you are trying to send across a message, a file may be, and you want the data to be intact when the receiver receives it. That whatever you send is received at the other end as is. You can make use of an encoding scheme to ensure that nothing goes missing.

Many times it has been observed (in XMLs) that special characters like ™ symbol are interpreted as their Hexadecimal variant: &#x2122. To translate something like that becomes an unnecessary overhead. To take care of such issues we can choose to encode our message first and then transmit it, and then, later on, decode it once the transmission is successful.

The resultant message would be as it had been once transmitted. Thus we can maintain the integrity of our message.

Base64 Encoding Scheme

While there are tons of encoding schemes available, we are going to see Base64 in our how to encode and decode a message in Java tutorial. Base64 represents binary data in an ASCII String format like other binary to text encoding schemes.

A lot of times your compiler fails to interpret a special character or when you are sending a file across a network it modifies the data as per its understanding. XMLs and emails over MIME are victims to that. That’s where message encoding and decoding via Base64 should primarily be used.

We are going to see a simple example of how a text file should be encoded and sent across. Then we will decode it read the content on the console. Even though I will create two classes with main methods here, the behaviour, as should be understood, would be something similar to a transmitter and receiver over a network.

How to Encode and Decode a Message in Java

I have made you a step by step tutorial on how to encode and decode a message in Java. Just follow these simple steps and you will see how easy it is to encode and decode a message.

The first thing that you need is a folder with the message you wish to transmit. That and two classes with main methods in each, one treating itself as a Sender and the other as a Receiver.

Here’s a screenshot of my folder structure that I have created in Eclipse.

folder structure in place for encoding and decoding example in java

NOTE: I hope by now you understand how to navigate, create classes, packages, folders and text files, in short how to move about in Eclipse. If you don’t, you can go back to our previous tutorials to get a proper handle. Any questions related to how I have created them you can shoot them in the comments section.

The message that I have put in the sentMessage.txt file is:

I know what you did last summer…

Let’s see if we can encode it and send using our Sender class, and then decode it through our Receiver class.

Here’s what I currently have in both my sender and receiver classes:

sender and receiver java classes with main methods

Sender Class to Encode a Message

To learn how to encode and decode a message in Java, let’s start with our sender class first where we will write a code to encode our existing message.

The first thing we gotta do is read the text file mentioned above. You can bring to use all the knowledge that you had acquired when we had seen How to Read a Text File tutorial.

Step 1: Type the following to locate the file to be read:

File file1 = new File(System.getProperty("user.dir") + "//Messages//sentMessage.txt");

Here you can choose to replace “System.getProperty(“user.dir”) + “//Messages//sentMessage.txt” with the actual location of your file. Since mine is located in my project folder the above is the correct way to write.

If there are errors encountered simply import the following atop:

import java.io.File;

Step 2: Put it in a BufferedReader to leverage the readLine() method. You can do so by using the following piece:

BufferedReader br = new BufferedReader(new FileReader(file1));

We are making use of FileReader class to read the content of the file here. Import the following packages to get rid of the errors:

import java.io.BufferedReader;
import java.io.FileReader;

You might be required to use a try-catch or you might encounter an IOException. You can alternatively choose to use throws in your method to use it at a later stage.

I am using a try-catch to handle it right away:

try catch around bufferedReader

Step 3: Time to make use of BufferedReader’s readLine() method to read everything the text file has. We will make use of the while loop here. Type in the following in the code:

 while((line = br.readLine()) != null) {
 

 }

Declare and initialize the variable ‘line’ as:

static String line = " ";

in the Class structure.

Why are we making it static? Go back to understand that we can’t use a non-static variable in a static method.

So the code you have so far would look something like this:

while loop to use BufferedReader

The Actual Encoding

Step 4: In the while loop block mentioned above we will mention what needs to be done to the read file. The real encoding of our text happens here:

Base64.getEncoder().encodeToString(line.getBytes());

To get rid of the Base64 error, import the following package:

import java.util.Base64;

The encodeToString method is basically the method that encodes the text into its binary equivalent. We use the getBytes() method to retrieve the data from the file as a parameter of encodeToString().

Now we need to put the encoded text in a separate file, right? …to be sent across?

So let’s create a static String variable called ‘encodedStuff’ and use it to retrieve the encoded data.

Step 5: Type:

static String encodedStuff = " ";

in the Class structure.

Step 6: Now use this ‘encodedStuff’ to retrieve the encoded data like this:

 encodedStuff = Base64.getEncoder().encodeToString(line.getBytes());

Confused?

Here’s the code so far:

encodedStuff in a variable

Writing to a New File

Step 7: Now time to write the encodedStuff in another file. Create another file called file2 using the same File class:

 File file2 = new File(System.getProperty("user.dir") + "//Messages//receivedMessage.txt");

I have called it receivedMessage.txt.

I have put it right next to the previous file declaration that we did:

file declaration placed with each other

Step 8: Let’s use FileWriter to write to file2. Type the following outside the while loop:

FileWriter fw = new FileWriter(file2);

To get rid of the errors import the following:

import java.io.FileWriter;

Step 9: The following code will actually write the encodedStuff in the file2 which is receivedMessage.txt:

fw.write(encodedStuff);

Step 10: Close the FileWriter instance by using the following:

fw.close();

That’s it for the Sender class. Here’s a picture of the whole code in a nutshell:

sender class whole code for encoding how to encode and decode a message in Java

Step 11: Run the above code to see what it does.

receivedMessage text file

On executing the above Sender class you will notice a text file receivedMessage.txt get created. If it doesn’t simply refresh the folder and it will begin to show.

Step 12: Open the file to see its content. It might have something gibberish like this:

SSBrbm93IHdoYXQgeW91IGRpZCBsYXN0IHN1bW1lci4uLg==

Now is the time to decode it.

Receiver Class to Decode a Message

Now that we are past the encoding phase, we need to decode the message that we have received. So let’s move on to the decoding section of how to encode and decode a message in Java.

Let’s open our Receiver Class:

Step 13: We are basically reading the receivedMessage.txt file here, so how do we do that?

File file = new File(System.getProperty(“user.dir”) + “//Messages//receivedMessage.txt”);

Right….

Use the following import package:

import java.io.File;

to get rid of the errors.

Step 14: As seen in Step 3, we will recreate the BufferedReader class and leverage its readLine() method in a while loop:

try {
 BufferedReader br = new BufferedReader(new FileReader(file));
 while((line = br.readLine())!=null) {

 }  
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

Let’s put the code that matters in the while loop now.

Step 15: Type the following in while loop:

 String decodedStuff = new String(Base64.getDecoder().decode(line));

It will make use of the decode method to decode the receivedMessage. We are simply creating a new String instance to retrieve the message in String format.

Step 16: Now you want to display the message on the console. What do you use for it? sysout…..right answer!

System.out.println(decodedStuff);

Here’s a glimpse of what all I had entered in Receiver class:

Receiver class full code how to encode and decode a message in Java

Step 17: Time to run the program.

message received info

OMG! How does he know? :O

That’s it! You have learned How to Encode and Decode a Message in Java.

I hope you understand that I am basically trying to simulate the whole sender-receiver transaction right? The behaviour is such as if a receiver on a different system has received this encoded message and is trying to decode it using his Receiver class.

Here’s a website to encode stuff directly without having to write all the code:

https://www.base64encode.org/

Alright! That’s it from my side.

SGFzdGEgbGEgdmlzdGE=

Now decode that!

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply