1. OverviewConverting between Blob and String in Java is usually done by converting the data to a byte array first. The java.sql.Blob interface is typically used when interacting with relational databases. The most crucial detail is specifying the character encoding (like UTF-8) when converting between a byte array and a String to prevent data corruption, especially with non-ASCII characters.This tutorial covers the implementation and testing of utility methods for converting a Java String to a java.sql.Blob object and vice versa. This is a common requirement when persisting text data, especially multi-byte character strings, into a database column designed to store binary large objects (BLOBs). We use the UTF-8 character set to ensure full support for standard ASCII and special/international characters.2. Maven SetupTo use the provided JUnit 5 test class, we need to include the JUnit Jupiter API and Engine dependencies in our pom.xml. The conversion utility itself only relies on standard JDK classes: org.junit.jupiter junit-jupiter-api 5.10.1 test org.junit.jupiter junit-jupiter-engine 5.10.1 test 3. Converting Blob to StringFor converting Blob to String, we read the byte content from a Blob object and convert it back into a Java String using UTF-8 encoding.The blobToString method handles null and empty Blob objects and includes a check for excessively large BLOBs (greater than Integer.MAX_VALUE bytes) to prevent conversion errors since Blob.getBytes() requires an int length. This method returns the String representation of the Blob data:public static String blobToString(Blob blob) throws SQLException { if (blob == null) { return null; } long length = blob.length(); if (length == 0) { return ""; } if (length > Integer.MAX_VALUE) { throw new SQLException("Blob is too large for a single String conversion."); } byte[] bytes = blob.getBytes(1, (int) length); return new String(bytes, StandardCharsets.UTF_8);}First, we perform a check for zero length to avoid the error “SerialException: Invalid arguments”. Accordingly, we obtain the entire Blob content as a byte array, with the position starting at 1. Then, we convert the byte array to a String using the UTF-8 charset. This method throws SQLException if a database access error occurs.4. Converting String to BlobFor converting a String to a Blob, we first convert the String into a byte array using UTF-8 encoding. Then, we wrap the byte array in a SerialBlob object, which is a concrete, serializable implementation of Blob.The stringToBlob method converts a Java String into a java.sql.Blob:public static Blob stringToBlob(String text) throws SQLException { if (text == null) { return null; } byte[] bytes = text.getBytes(StandardCharsets.UTF_8); return new SerialBlob(bytes);}Note that this method is safe even for an empty string (“”), which results in a zero-length byte array. This method throws SQLException if a database access error occurs.5. Testing Bi-Directional ConversionNext, we verify the bi-directional conversion (String -> Blob -> String) for various inputs to ensure data integrity and proper handling of edge cases.5.1. Converting a Standard ASCII StringWe start with a standard ASCII String, convert it to a Blob, and then convert the Blob back to a String object. We assert that the String->Blob conversion is OK, by comparing the original String with the String converted back from the Blob:@Testvoid givenStandardAsciiString_whenPerformingConversion_thenConversionSuccessful() throws SQLException { String originalString = "Hello, world!"; Blob blob = BlobStringConverter.stringToBlob(originalString); assertNotNull(blob); String convertedString = BlobStringConverter.blobToString(blob); assertEquals(originalString, convertedString);}Note that we also verify that the Blob converted from the String isn’t null.5.2. Converting a String with Special CharactersThis time, let’s start with a String that includes special characters (e.g., international characters, emojis). This crucial test validates that the UTF-8 encoding/decoding correctly handles multi-byte characters without data loss or corruption. We start with an example String with non-ASCII characters (e.g., Japanese, German umlaut):@Testvoid givenStringWithSpecialCharacters_whenPerformingConversion_thenConversionSuccessful() throws SQLException { String originalString = "Test: こんにちは, äöü"; Blob blob = BlobStringConverter.stringToBlob(originalString); String convertedString = BlobStringConverter.blobToString(blob); assertEquals(originalString, convertedString);}Note that we again make the same assertion about the original String being equal to the converted String.5.3. Converting an Empty StringLet’s start with an empty String, convert it to a Blob, and then back to a String:@Testvoid givenEmptyString_whenPerformingConversion_thenConversionSuccessful() throws SQLException { String originalString = ""; Blob blob = BlobStringConverter.stringToBlob(originalString); String convertedString = BlobStringConverter.blobToString(blob); assertEquals(originalString, convertedString);}Note that for the assertEquals test to pass, an empty string (“”) must convert to a zero-length Blob and back to an empty String.5.4. Converting a null StringLet’s start with a null String, convert it to a Blob, and then convert the Blob back to a String:@Testvoid givenNullString_whenPerformingConversion_thenConversionSuccessful() throws SQLException { assertNull(BlobStringConverter.stringToBlob(null), "stringToBlob should return null for null input."); assertNull(BlobStringConverter.blobToString(null), "blobToString should return null for null input.");}This test confirms that null input to either conversion method results in a null output, correctly handling database null values.6. ConclusionIn this article, we explored how to convert a Blob to a String and a String to a Blob. By consistently using UTF-8 encoding, we can reliably perform bi-directional conversion between Java String objects and java.sql.Blob objects. Furthermore, we tested conversion for a wide range of characters and correctly managed edge cases, such as null and empty inputs.As always, the full code for the examples is available over on GitHub.The post Converting Blob to String and String to Blob in Java first appeared on Baeldung.