Java Convert File to Base64 String
Tags: Java Base64
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.
FileToBase64StringExample1.java
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=
Happy Coding 😊