- utsengar / EncodeBased64Binary.java
- Java Base64 Encoding and Decoding
- 1. Overview
- Further reading:
- Guide to Java URL Encoding/Decoding
- SHA-256 and SHA3-256 Hashing in Java
- New Password Storage in Spring Security 5
- 2. Java 8 for Base 64
- 2.1. Java 8 Basic Base64
- 2.2. Java 8 Base64 Encoding Without Padding
- 2.3. Java 8 URL Encoding
- 2.4. Java 8 MIME Encoding
- 3. Encoding/Decoding Using Apache Commons Code
- 4. Converting a String to a byte Array
- 5. Conclusion
- Java Convert File to Base64 String
- How to convert a File to Base64 String in Java
utsengar / EncodeBased64Binary.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import org . apache . commons . codec . binary . Base64 ; |
private String encodeFileToBase64Binary ( String fileName ) |
throws IOException |
File file = new File ( fileName ); |
byte [] bytes = loadFile ( file ); |
byte [] encoded = Base64 . encodeBase64 ( bytes ); |
String encodedString = new String ( encoded ); |
return encodedString ; |
> |
private static byte [] loadFile ( File file ) throws IOException |
InputStream is = new FileInputStream ( file ); |
long length = file . length (); |
if ( length > Integer . MAX_VALUE ) |
// File is too large |
> |
byte [] bytes = new byte [( int ) length ]; |
int offset = 0 ; |
int numRead = 0 ; |
while ( offset < bytes . length |
&& ( numRead = is . read ( bytes , offset , bytes . length — offset )) >= 0 ) |
offset += numRead ; |
> |
if ( offset < bytes . length ) |
throw new IOException ( «Could not completely read file » + file . getName ()); |
> |
is . close (); |
return bytes ; |
> |
Java Base64 Encoding and Decoding
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this tutorial, we explore the various utilities that provide Base64 encoding and decoding functionality in Java.
We’re mainly going to illustrate the new Java 8 APIs. Also, we use the utility APIs of Apache Commons.
Further reading:
Guide to Java URL Encoding/Decoding
SHA-256 and SHA3-256 Hashing in Java
New Password Storage in Spring Security 5
A quick guide to understanding password encryption in Spring Security 5 and migrating to better encryption algorithms.
2. Java 8 for Base 64
Java 8 has finally added Base64 capabilities to the standard API, via the java.util.Base64 utility class.
Let’s start by looking at a basic encoder process.
2.1. Java 8 Basic Base64
The basic encoder keeps things simple and encodes the input as-is, without any line separation.
The encoder maps the input to a set of characters in the A-Za-z0-9+/ character set.
Let’s first encode a simple String:
String originalInput = "test input"; String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
Note how we retrieve the full Encoder API via the simple getEncoder() utility method.
Let’s now decode that String back to the original form:
byte[] decodedBytes = Base64.getDecoder().decode(encodedString); String decodedString = new String(decodedBytes);
2.2. Java 8 Base64 Encoding Without Padding
In Base64 encoding, the length of an output-encoded String must be a multiple of four. If necessary, the encoder adds one or two padding characters (=) at the end of the output as needed in order to meet this requirement.
Upon decoding, the decoder discards these extra padding characters. To dig deeper into padding in Base64, check out this detailed answer on Stack Overflow.
Sometimes, we need to skip the padding of the output. For instance, the resulting String will never be decoded back. So, we can simply choose to encode without padding:
String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
2.3. Java 8 URL Encoding
URL encoding is very similar to the basic encoder. Also, it uses the URL and Filename Safe Base64 alphabet. In addition, it does not add any line separation:
String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java"; String encodedUrl = Base64.getUrlEncoder().encodeToString(originalURL.getBytes());
Decoding happens in much the same way. The getUrlDecoder() utility method returns a java.util.Base64.Decoder. So, we use it to decode the URL:
byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl); String decodedUrl = new String(decodedBytes);
2.4. Java 8 MIME Encoding
Let’s start by generating some basic MIME input to encode:
private static StringBuilder getMimeBuffer() < StringBuilder buffer = new StringBuilder(); for (int count = 0; count < 10; ++count) < buffer.append(UUID.randomUUID().toString()); >return buffer; >
The MIME encoder generates a Base64-encoded output using the basic alphabet. However, the format is MIME-friendly.
Each line of the output is no longer than 76 characters. Also, it ends with a carriage return followed by a linefeed (\r\n):
StringBuilder buffer = getMimeBuffer(); byte[] encodedAsBytes = buffer.toString().getBytes(); String encodedMime = Base64.getMimeEncoder().encodeToString(encodedAsBytes);
In the decoding process, we can use the getMimeDecoder() method that returns a java.util.Base64.Decoder:
byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime); String decodedMime = new String(decodedBytes);
3. Encoding/Decoding Using Apache Commons Code
First, we need to define the commons-codec dependency in the pom.xml:
commons-codec commons-codec 1.15
The main API is the org.apache.commons.codec.binary.Base64 class. We can initialize it with various constructors:
- Base64(boolean urlSafe) creates the Base64 API by controlling the URL-safe mode (on or off).
- Base64(int lineLength) creates the Base64 API in a URL-unsafe mode and controls the length of the line (default is 76).
- Base64(int lineLength, byte[] lineSeparator) creates the Base64 API by accepting an extra line separator, which by default is CRLF (“\r\n”).
Once the Base64 API is created, both encoding and decoding are quite simple:
String originalInput = "test input"; Base64 base64 = new Base64(); String encodedString = new String(base64.encode(originalInput.getBytes()));
Moreover, the decode() method of the Base64 class returns the decoded string:
String decodedString = new String(base64.decode(encodedString.getBytes()));
Another option is using the static API of Base64 instead of creating an instance:
String originalInput = "test input"; String encodedString = new String(Base64.encodeBase64(originalInput.getBytes())); String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));
4. Converting a String to a byte Array
Sometimes, we need to convert a String to a byte[]. The simplest way is to use the String getBytes() method:
String originalInput = "test input"; byte[] result = originalInput.getBytes(); assertEquals(originalInput.length(), result.length);
We can provide encoding as well and not depend on default encoding. As a result, it’s system-dependent:
String originalInput = "test input"; byte[] result = originalInput.getBytes(StandardCharsets.UTF_16); assertTrue(originalInput.length() < result.length);
If our String is Base64 encoded, we can use the Base64 decoder:
String originalInput = "dGVzdCBpbnB1dA=="; byte[] result = Base64.getDecoder().decode(originalInput); assertEquals("test input", new String(result));
We can also use the DatatypeConverter parseBase64Binary() method:
String originalInput = "dGVzdCBpbnB1dA=="; byte[] result = DatatypeConverter.parseBase64Binary(originalInput); assertEquals("test input", new String(result));
Finally, we can convert a hexadecimal String to a byte[] using the DatatypeConverter.parseHexBinary method:
String originalInput = "7465737420696E707574"; byte[] result = DatatypeConverter.parseHexBinary(originalInput); assertEquals("test input", new String(result));
5. Conclusion
This article explained the basics of how to do Base64 encoding and decoding in Java. We used the new APIs introduced in Java 8 and Apache Commons.
Finally, there are a few other APIs that provide similar functionality: java.xml.bind.DataTypeConverter with printHexBinary and parseBase64Binary.
Code snippets can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you'll have results within minutes:
Java Convert File to Base64 String
In this Java tutorial we learn how to convert a binary file, image file or text file into Base64 encoded String in Java programming language.
How to convert a File to Base64 String in Java
In Java to convert a file to Base64 String object firstly we need to read all bytes of the file and then use the Base64.getEncoder().encodeToString() method to encode it to Base64 String.
byte[] byteData = Files.readAllBytes(Paths.get("/path/to/the/file")); String base64String = Base64.getEncoder().encodeToString(byteData);
For example, we have an image file at D:\SimpleSolution\qrcode.png, the following Java program to show you how to convert this image file to a Base64 String.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; public class FileToBase64StringExample1 public static void main(String. args) throws IOException // Read all bytes from a file and convert to Base64 String byte[] byteData = Files.readAllBytes(Paths.get("D:\\SimpleSolution\\qrcode.png")); String base64String = Base64.getEncoder().encodeToString(byteData); System.out.println(base64String); > >
iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQAAAABYmaj5AAAA7ElEQVR42tXUsZHEIAwFUHk2cHZuQDO0QeaWTAN4twK3REYbzNAAyhww1ombvd1NbBHeMQS8CPERAH+MAn9YBWCBzAEGTcR13W8cZaEpoLdpiuA6tIb86JWhHnH1tq7vyk4l53MR3fu0p2pZzbJ8JXiqYtHP6H53uBAH3mKadpg0HRZhRrCZNBHzxnWIadBUbILRbK/KzkXxRhEHNpumMuLXLPOZ4IVoz4flA5LTlTzkO+CkqeU/Sgy65G59q92QptbXLIEZVhXQsblDlxZIy8iPDsmrIn5mdiWui/QCoKr2pq35CUPRf/nBPvUNct67nP2Y9j8AAAAASUVORK5CYII=