How to Convert BLOB to Byte Array in Java Using InputStream

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

  1. Connect to the Database: We’ll start by establishing a connection to the MySQL database using DriverManager.
  2. Retrieve the BLOB: After executing the SQL query, we’ll retrieve the BLOB from the result set and process it using an InputStream.
  3. Convert to Byte Array: We’ll read the BLOB data in chunks through the InputStream and convert it into a byte array.
  4. 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

  1. Database Connection:
    • We use DriverManager.getConnection() to establish a connection to the MySQL database with the provided credentials.
  2. Retrieving BLOB as InputStream:
    • Blob.getBinaryStream() is used to retrieve the BLOB data as an InputStream, allowing us to read the binary data in small chunks.
  3. Reading the BLOB Data:
    • We use a ByteArrayOutputStream to store the BLOB data in memory. This method reads chunks of data from the InputStream and writes them to the ByteArrayOutputStream.
  4. Conversion to Byte Array:
    • Once the data is fully read, the toByteArray() method is called to convert the data into a byte array.
  5. Resource Management:
    • Both the InputStream and ByteArrayOutputStream are explicitly closed to free resources. We also ensure that the database connection, statement, and result set are properly closed.

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, ...]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top