In this guide, we’ll explore how to convert a BLOB (Binary Large Object) into a byte array in Java using a different approach than the usual getBytes()
method. We’ll focus on using the InputStream
method to efficiently read the BLOB data from a database.
What is a BLOB?
A BLOB is a type of data stored in databases that can hold a large amount of binary data, such as images, audio files, or other multimedia. The BLOB datatype is often used in MySQL and comes in four main types based on the size of data they can store:
- TINYBLOB
- BLOB
- MEDIUMBLOB
- LONGBLOB
In this tutorial, we’ll demonstrate how to convert BLOB data retrieved from a MySQL database into a byte array that can be processed in Java.
Steps to Convert BLOB to Byte Array Using InputStream
To achieve this, we’ll use JDBC (Java Database Connectivity) to interact with MySQL and InputStream
to read the BLOB. This method is helpful when you’re dealing with large data and need to process it in smaller chunks.
Step-by-Step Code Explanation
- Connect to the Database: We’ll start by establishing a connection to the MySQL database using
DriverManager
. - Retrieve the BLOB: After executing the SQL query, we’ll retrieve the BLOB from the result set and process it using an
InputStream
. - Convert to Byte Array: We’ll read the BLOB data in chunks through the
InputStream
and convert it into a byte array. - Release Resources: It’s important to close the
InputStream
and other resources after processing the BLOB data to avoid memory leaks.
Java Code
import java.sql.*; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; public class BlobToByteArrayExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydb"; String username = "root"; String password = "password"; String query = "SELECT my_custom_image FROM your_table"; Connection conn = null; Statement stmt = null; ResultSet resultSet = null; InputStream inputStream = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("Connecting to the database..."); conn = DriverManager.getConnection(url, username, password); System.out.println("Connection is successful!"); stmt = conn.createStatement(); resultSet = stmt.executeQuery(query); while (resultSet.next()) { Blob blob = resultSet.getBlob("my_custom_image"); inputStream = blob.getBinaryStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] byteArray = outputStream.toByteArray(); System.out.println("BLOB converted to Byte Array: " + Arrays.toString(byteArray)); outputStream.close(); inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (resultSet != null) resultSet.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Code Breakdown
- Database Connection:
- We use
DriverManager.getConnection()
to establish a connection to the MySQL database with the provided credentials.
- We use
- Retrieving BLOB as InputStream:
Blob.getBinaryStream()
is used to retrieve the BLOB data as anInputStream
, allowing us to read the binary data in small chunks.
- Reading the BLOB Data:
- We use a
ByteArrayOutputStream
to store the BLOB data in memory. This method reads chunks of data from theInputStream
and writes them to theByteArrayOutputStream
.
- We use a
- Conversion to Byte Array:
- Once the data is fully read, the
toByteArray()
method is called to convert the data into a byte array.
- Once the data is fully read, the
- Resource Management:
- Both the
InputStream
andByteArrayOutputStream
are explicitly closed to free resources. We also ensure that the database connection, statement, and result set are properly closed.
- Both the
Output Example
Here’s an example output that the program might print (with a small example byte array):
Connecting to the database... Connection is successful! BLOB converted to Byte Array: [12, 45, 67, 23, 54, ...]