How to convert Byte Array to BLOB in java

By Saruque Ahamed Mollick

In this Java tutorial, I will show you how to convert Byte array to BLOB in Java. In CodeSpeedy I always try to give you the best and easy solution to any coding problem. But as we all know there is not only a single solution to a problem. So always try to find a better solution. If you find something better or easy post it in the below comment section. You are always welcome to comment.

In my previous article, I have shared an easy example on How to convert BLOB to Byte Array in java

So I thought this time I should explain how to convert byte array to BLOB in Java.

If you wish you can learn about BLOB from here – What is BLOB Data Type?

Convert Byte Array to BLOB in Java with an Easy Example

Look at the below Java Code:

import java.io.*;
import java.sql.Blob;
import java.util.*;
import javax.sql.rowset.serial.*;

public class MyClass {
   public static void main(String[] args) throws Exception {
      Scanner my_scanner = new Scanner(new BufferedReader(new FileReader("my_file.txt"))); // you can put your file path here with file name
      Blob my_blob= null; // create a BLOB
      while(my_scanner.hasNext()) {
         byte[] my_byte_array= my_scanner.nextLine().getBytes(); // convert your file to Byte Array
         my_blob = new SerialBlob(my_byte_array); // convert Byte array to BLOB using SerialBlob() method
      }
   }
}

I hope the above example is easy enough to understand.



Explanation:

  • At first, I have created an object of Scanner class and read my file using FileReader() method.
  • Then created a BLOB  object initialized with null
  • Next, I have Converted the file into a Byte array ( byte[] ),  stored it into my_byte_array.
  • Finally converted the byte array into BLOB using SerialBlob() method.

Also read,

Guess The Number Game Using Java with Source Code

How to convert Java Array to JSON array?

Leave a Reply

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