You already using apache commons-codec so I recommend adding commons-io for reading the file. That way you can remove your loadFile() method and just have:
private static String encodeFileToBase64Binary(String fileName) throws IOException {
File file = new File(fileName);
byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(file));
return new String(encoded, StandardCharsets.US_ASCII);
}
Answer from gfelisberto on Stack OverflowHow to do in Java
howtodoinjava.com › home › java security › java base64 encode and decode a file (with examples)
Java Base64 Encode and Decode a File (with Examples)
April 19, 2024 - Since Java 8, the java.util.Base64 class provides convenient methods for encoding and decoding files such as text, image, JSON files.
Top answer 1 of 4
42
You already using apache commons-codec so I recommend adding commons-io for reading the file. That way you can remove your loadFile() method and just have:
private static String encodeFileToBase64Binary(String fileName) throws IOException {
File file = new File(fileName);
byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(file));
return new String(encoded, StandardCharsets.US_ASCII);
}
2 of 4
37
Here is a solution without any required dependencies (Apacha et al.) requiring only JDK 8+:
import java.util.Base64;
import java.nio.file.Files;
private static String encodeFileToBase64(File file) {
try {
byte[] fileContent = Files.readAllBytes(file.toPath());
return Base64.getEncoder().encodeToString(fileContent);
} catch (IOException e) {
throw new IllegalStateException("could not read file " + file, e);
}
}
Java Code Geeks
javacodegeeks.com › home › core java
Java 8 Base64 Encoding and Decoding (With Examples) - Java Code Geeks
September 8, 2020 - Returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme. This is a simple encoding technique in the Base64. The encoded string will contain only “A-Za-z0-9+/” these characters set and considers the new line character as line breaker in decoding. Let us see the example you will understand clearly.
Medium
medium.com › @AlexanderObregon › javas-base64-getencoder-method-explained-d3c331139837
Java’s Base64.getEncoder() Method Explained | Medium
October 22, 2024 - When transmitting files over the web, such as when uploading images or documents, Base64 encoding can be used to represent the binary content of a file in a way that can be transmitted via HTTP. For instance, let’s say you are transmitting a binary file over a web API: import java.util.Base64; import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class FileBase64Encoding { public static void main(String[] args) { try { // Read the file as bytes byte[] fileContent = Files.readAllBytes(Paths.get("path/to/file.txt")); // Get Base64 encoder Base64.Encoder encoder = Base64.getEncoder(); // Encode the file content into a Base64 string String encodedFile = encoder.encodeToString(fileContent); System.out.println("Encoded File Content: " + encodedFile); } catch (IOException e) { e.printStackTrace(); } } }
Base64.Guru
base64.guru › home › developers › java
Java Base64 Encode | Java | Developers | Base64
import java.util.Base64; class Base64Encode { public static void main(String[] args) { String str = "guru"; String b64 = Base64.getEncoder().encodeToString(str.getBytes()); System.out.println(b64); //-> "Z3VydQ==" } } I hope you enjoy this discussion. In any case, I ask you to join it.
Codetinkering
codetinkering.com › base64-data-java-example
Base64 Stream Examples in Java – Code Tinkering
The following code reads a Base64 Encoded file on the disk (decoding it in the process) and then re-encodes the file into base64, writing those bytes to the first socket connection the ServerSocket receives. import org.apache.commons.codec.binary.Base64InputStream; import org.apache.commons.codec.binary.Base64OutputStream; import java.io.FileInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketBase64 { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(5555); Socket socket = serve
Developers Corner
avaldes.com › base64-encoding-and-decoding-examples-in-java-8
Base64 Encoding and Decoding Examples in Java 8
October 24, 2016 - In this example we will be reading a file ‘shakespeare_b64.txt’ that contains base64 encoded data from our InputStream. To make it easier to work with streams, Java 8 has added the wrap() method which will automatically perform the encoding or decoding of the data as it arrives in the input ...
Base64.Guru
base64.guru › home › developers › java › examples
Convert PDF to Base64 in Java | Examples | Java | Developers | Base64
To encode a PDF file to Base64 you have to read all file bytes and encode them to Base64 using the Base64.Encoder class. Please keep in mind, that the example below prints the Base64 string to console, so use only small PDF files for tests or write the output into a text file. import java.io.File; import java.nio.file.Files; import java.util.Base64; class Base64EncodePdf { public static void main(String[] args) { try { File file = new File("./test.pdf"); byte [] bytes = Files.readAllBytes(file.toPath()); String b64 = Base64.getEncoder().encodeToString(bytes); System.out.println(b64); //-> "JVBERi..."
HowToDoInJava
howtodoinjava.com › home › java 8 › java base64 encode and decode example
Java Base64 Encode and Decode Example
April 19, 2024 - This Java tutorial discussed the base64 encode and decode examples using the Java 8 java.util.Base64 class and its inner classes.
Javatpoint
javatpoint.com › java-base64-encode-decode
Java Base64 Encode Decode - javatpoint
Java Base64 Encode Decode examples and topics on functional interface, anonymous class, lambda for list, lambda for comparable, default methods, method reference, java date and time, java nashorn, java optional, stream, filter etc.
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Base64.Encoder.html
Base64.Encoder (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
Stack Abuse
stackabuse.com › encoding-and-decoding-base64-strings-in-java
Encoding and Decoding Base64 Strings in Java
September 7, 2023 - It can be part of an image, it can be a part of an audio file or it can be a command that deletes half of your hard drive. This data must be processed differently, depending on what it's supposed to represent. Also, many servers don't expect raw binary data. Email servers, for example, expect textual data. All emails are encoded before the applications send them. Java 8 introduced us to a new class - Base64...
MyCompiler
mycompiler.io › guides › base64-encoding-decoding-in-java
myCompiler - An online IDE for C, C++, Java, Python, Go, NodeJS and other languages
Run your favourite programming languages online with myCompiler. Simple and easy to use IDE where you can edit, compile and run your code in the programming language of your choice
Apache Commons
commons.apache.org › proper › commons-codec › jacoco › org.apache.commons.codec.binary › Base64.java.html
Base64.java - Apache Commons
* <p> * This implementation is aligned with * <a href="https://datatracker.ietf.org/doc/html/rfc4648#:~:text=Table 2: The "URL and Filename safe" Base 64 Alphabet">RFC 4648 * Table 2: The "URL and Filename safe" Base 64 Alphabet</a>. This method skips unknown or unsupported characters. * </p> * * @param base64String String containing Base64 data. * @return New array containing decoded data. * @since 1.21 */ public static byte[] decodeBase64UrlSafe(final String base64String) { return builder().setDecodeTableFormat(DecodeTableFormat.URL_SAFE).get().decode(base64String); } /** * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature.