Program to convert Byte array to blob in java
In Java, converting a byte array to a 'Blob' object can be done using the 'javax.sql.rowset.serial.SerialBlob' class, which implements the 'java.sql.Blob' interface.
import java.sql.Blob;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;
import java.sql.SQLException;
public class ByteArrayToBlobExample {
public static void main(String[] args) {
// Example byte array
byte[] byteArray = {1, 2, 3, 4, 5};
try {
// Convert byte array to Blob
Blob blob = new SerialBlob(byteArray);
// Use the Blob as needed
// For demonstration, printing the Blob length
System.out.println("Blob length: " + blob.length());
} catch (SerialException | SQLException e) {
e.printStackTrace();
}
}
}
The provided code snippet creates a 'Blob' object from a byte array and prints the length of the 'Blob'. Let’s go through the output step-by-step.
- Byte Array: The byte array
'{1, 2, 3, 4, 5}'is provided. - Blob Creation: The
'SerialBlob'constructor is used to convert the byte array into a'Blob'. - Printing Blob Length: The length of the
'Blob'is obtained using the'length()'method and printed.
Output:
Blob length: 5
This output indicates that the 'Blob' object has been successfully created with the length of 5 bytes, corresponding to the length of the input byte array.
Key Points
'SerialBlob(byte[] bytes)': This constructor creates a'SerialBlob'object that wraps the specified byte array.- Exception Handling:
'SerialBlob'may throw `SerialException