Convert base64 to file in java

Base64 Stream Examples in Java

The following examples use Apache’s Commons Codec library which is available on Maven Central by using the following dependency in your pom.xml file.

dependency> groupId>commons-codecgroupId> artifactId>commons-codecartifactId> version>1.15version> dependency> 

Reading and Writing a Base64 String Example

The following code will allow you to read or decode a Base64 encoded String in Java. This is useful for data that is short or limited in length. Note that there are two steps involved in this process:

  • First, we decode the data back into a binary format using the Base64 class’s decodeBase64 helper method. If your data was only binary data to begin with, you can simply use the data as it returns.
  • Second, since my original data was UTF-8 encoded text I convert that binary data back into a String using Apache’s StringUtils class.
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.StringUtils; public class Base64Example  public static void main(String[] args)  // An example of a Base64 encoded String String base64 = "SGVsbG8gV29ybGQhIFRoaXMgaXMgYW4gZXhhbXBsZSBvZiBCYXNlNjQgZW5jb2RlZCBkYXRhLg= token punctuation">; // Decode the Base64 String and get a byte array containing the data byte[] bytes = Base64.decodeBase64(base64); // Convert the byte array to a UTF-8 String String utf8 = StringUtils.newStringUtf8(bytes); System.out.println(utf8); > > 

Reading Base64 Data from a File Stream Example

The following code uses Apache’s Base64InputStream to read base64 data and decode it in a conventional stream type of format.

This is useful for decoding large amounts of Base64 encoded data or used within processes where data is consumed using a stream. You can simply wrap a FileInputStream with the Base64InputStream so base64 data is automatically decoded as you consume bytes from an InputStream.

// An example of a Base64 encoded String String base64 = "SGVsbG8gV29ybGQhIFRoaXMgaXMgYW4gZXhhbXBsZSBvZiBCYXNlNjQgZW5jb2RlZCBkYXRhLg= token punctuation">; // Write our Base64 String into a text file try (FileWriter fileWriter = new FileWriter("base64.txt"))  fileWriter.write(base64); > // Use Apache's Base64InputStream to read the data in from our file try (Scanner scanner = new Scanner(new Base64InputStream(new FileInputStream("base64.txt"))))  while (scanner.hasNextLine())  // Print the line to the console System.out.println(scanner.nextLine()); > > 

Reading Base64 data from a Socket InputStream

The following code can be used in tandem with the next section’s code on using a ServerSocket to write data. Simply run this codebase after starting the following server socket code.

We can even wrap a Java Socket’s InputStream with a Base64InputStream so that all of the data is sent over the network encoded in base64 format.

  • This is sometimes helpful when writing binary data to a socket that also sends zero or null byte terminated-strings. This way the low bytes of the binary data do not interfere with the newline or zero byte characters of the stream.
  • Additionally, this can be useful when attempting to send encrypted data over a socket in the same fashion, as what was originally a String is changed to bytes ranging from 0-255.
import org.apache.commons.codec.binary.Base64InputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Scanner; public class SocketReadBase64  public static void main(String[] args) throws IOException  Socket socket = new Socket(); // Connect to our server (localhost, port 5555) socket.connect(new InetSocketAddress("0.0.0.0", 5555)); // Wrap our Socket's InputStream with a Base64 InputStream try (Scanner scanner = new Scanner(new Base64InputStream(socket.getInputStream())))  while (scanner.hasNextLine())  // Print the line to the console System.out.println(scanner.nextLine()); > > > > 

Writing Base64 data using a ServerSocket OutputStream

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 = server.accept(); // Wrap the socket channel's OutputStream with a Base64OutputStream so data can be written back out in Base64 try (Base64OutputStream base64OutputStream = new Base64OutputStream(socket.getOutputStream()))  // Read and decode our base64 data file with a Base64InputStream wrapping a FileInputStream try (Base64InputStream base64InputStream = new Base64InputStream(new FileInputStream("base64.txt")))  // Write a single byte at a time to our outputstream. This can be further improved by using a buffer for (int data = base64InputStream.read(); data != -1; data = base64InputStream.read())  base64OutputStream.write(data); > > > > > 

Encode a file into base64 in Java

For comparison, here is how to encode a file into base64 without using streams. Note this will not scale well as it can consume large amounts of memory if you are converting a large file.

import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Base64; public class Base64Example  public static void main(String[] args) throws IOException  // Read the file into a byte array using try with resources File file = new File("path/to/file.txt"); byte[] data = new byte[(int) file.length()]; try (FileInputStream fis = new FileInputStream(file))  fis.read(data); > // Encode the byte array into base64 String encoded = Base64.getEncoder().encodeToString(data); // Write the encoded base64 string to a file File outputFile = new File("path/to/output.txt"); try (FileWriter fw = new FileWriter(outputFile))  fw.write(encoded); > > > 

Java Articles

See more of my articles on Java:

Источник

Convert base64 to file in java code example

Solution 1: The following code worked for me Solution 2: encode(«path/to/file»); decode(«path/to/file»); Solution 1: Apache POI is a good library to process excel files, here is a good tutorial to start with it, basically you have to convert your base base 64 file into an InputStream and from there use one of the WorkBook implementation that Apache POI provides to process the data. Solution 1: The decoded data isn’t plain text data — it’s just binary data.

Convert Compressed Base64 String into its original file

The following code worked for me

public static void main(String[] args) throws IOException, DataFormatException
public static boolean decode(String filename) < try < byte[] decodedBytes = Base64.decode(loadFileAsBytesArray(filename), Base64.DEFAULT); writeByteArraysToFile(filename, decodedBytes); return true; >catch (Exception ex) < return false; >> public static boolean encode(String filename) < try < byte[] encodedBytes = Base64.encode(loadFileAsBytesArray(filename), Base64.DEFAULT); writeByteArraysToFile(filename, encodedBytes); return true; >catch (Exception ex) < return false; >> public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException < File file = new File(fileName); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file)); writer.write(content); writer.flush(); writer.close(); >public static byte[] loadFileAsBytesArray(String fileName) throws Exception

Convert base64 to pdf in android studio Code Example, encode file to base64 java. java base64 to file. android ecode base64. decode base64 to file java. how to use base64.getdecoder () android. convert base64 to pdf in android studio. convert base64 to pdf and save android. convert to pdf from base64 android. convert base64 string to pdf android.

Convert base64 to excel file in java

Apache POI is a good library to process excel files, here is a good tutorial to start with it, basically you have to convert your base base 64 file into an InputStream and from there use one of the WorkBook implementation that Apache POI provides to process the data.

It makes no difference to Java if you have an image or an excel file. Below is a piece of exemplary code that I think should help you getting started. It is based on Write Base64-encoded image to file and the code provided there for decoding the base 64 encoded file and based on the instructions from https://www.codejava.net/java-se/jdbc/insert-file-data-into-mysql-database-using-jdbc. It should work for many databases as it is using only JDBC, but it is not tested against MySQL.

package net.codejava.jdbc; import org.apache.commons.codec.binary.Base64; import java.io.ByteArrayInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; class JdbcInsertFileTwo < public static void main(String[] args) < String base64encoded = "asdf123"; byte[] excelBytes = Base64.decodeBase64(base64encoded); String url = "jdbc:mysql://localhost:3306/contactdb"; String user = "root"; String password = "secret"; try (Connection conn = DriverManager.getConnection(url, user, password)) < PreparedStatement statement = conn.prepareStatement("insert into table(name, data) " + "values(. )"); statement.setString(1, "My file name.xls"); statement.setBinaryStream(2, new ByteArrayInputStream(excelBytes), excelBytes.length); int row = statement.executeUpdate(); if (row >0) < System.out.println("The excel file was uploaded."); >> catch (SQLException ex) < ex.printStackTrace(); >> > 

Spring boot — Convert base64 to excel file in java, 2 Answers. Apache POI is a good library to process excel files, here is a good tutorial to start with it, basically you have to convert your base base 64 file into an InputStream and from there use one of the WorkBook implementation that Apache POI provides to process the data. It makes no difference to Java if you …

Base 64 decode and write to doc file

The decoded data isn’t plain text data — it’s just binary data. So write it with a FileStream , not a FileWriter :

// If your Base64 class doesn't have a decode method taking a string, // find a better one! byte[] decodedBytes = Base64.decodeBase64(stringBase64); // Note the try-with-resources block here, to close the stream automatically try (OutputStream stream = new FileOutputStream("F:\\xxx.doc"))
byte[] decodedBytes = Base64.decodeBase64(stringBase64); Files.write(Paths.get("F:\\xxx.doc"), decodedBytes); 
 byte[] encodedBytes = /* your encoded bytes*/ // Decode data on other side, by processing encoded data byte[] decodedBytes= Base64.decodeBase64(encodedBytes ); String yourValue=new String(decodedBytes); System.out.println("Decoded String is " + yourValue); 

Now further you can write this string into a file and read further.

Java Base64 Encode Decode, Java provides a class Base64 to deal with encryption. You can encrypt and decrypt your data by using provided methods. You need to import java.util.Base64 in your source file to use its methods. This class provides three different encoders and decoders to encrypt information at each level. You can use these methods at the …

Base64-encode a file and compress it

BASE64 encoded data are usually longer than source, however you are using the length of the source data to write encoded to output stream.

You have use size of the generated array instead of your variable len .

Second notice — do not redefine buffer each time you encode a byte. Just write result into output.

 while ((len = in.read(buffer)) > 0)

UPDATE: Use Arrays.copyOf(. ) to set length of the input buffer for encoding.

Your main problem is that base64 encoding can not be applied block-wise (especially not the apache-commons implementation). This problem is getting worse because you don’t even know how large your blocks are as this depends on the bytes read by in.read(..) .

Therefore you have two alternatives:

  1. Load the complete file to memory and then apply the base64 encoding.
  2. use an alternative Base64 encoder implementation that works stream-based (the Apache Batik project seems to contain such an implementation: org.apache.batik.util.Base64EncoderStream)

When you read the file content into buffer you get len bytes. When base64 encoding this you get more than len bytes, but you still only write len bytes to the file. This beans that the last part of your read chunks will be truncated.

Also, if your read does not fill the entire buffer you should not base64 encode more than len bytes as you will otherwise get trailing 0s in the padding of the last bytes.

Combining the information above this means that you must base64 encode the whole file (read it all into a byte[]) unless you can guarantee that each chunk you read can fit exactly into a base64 encoded message. If your files are not very large I would recommend reading the whole file.

A smaller problem is that when reading in your loop you should probably check for «> -1», not «> 0», but int his case it does not make a difference.

Java — base 64 decode and write to doc file, The decoded data isn’t plain text data — it’s just binary data. So write it with a FileStream, not a FileWriter: // If your Base64 class doesn’t have a decode method taking a string, // find a better one! byte[] decodedBytes = Base64.decodeBase64(stringBase64); // Note the try-with-resources block here, …

Источник

Читайте также:  Python итерация вложенных словарей
Оцените статью