File to blob

Suppose you have a text file and it needs to be stored in a database column or transmitted over the network. If the solution is required in java, how would you do it ?
Solution is to convert the file into a byte array and store it in the database column or then transmit it over the network.
A blob data type is represented as a byte array
( byte[ ]) in java.

Solution

There are various methods to convert a file in a byte array or blob in java.

Method 1 : Reading File into a String

Read the file line by line using a java.util.BufferedReader and add it to a java.lang.StringBuffer.
Convert the contents of StringBuffer to a byte[] using getBytes() method of java.lang.String class as shown in the code below.

public static byte[] convertFileContentToBlob(String filePath) 
                     throws IOException {
  byte[] fileContent = null;
  // initialize string buffer to hold contents of file
  StringBuffer fileContentStr = new StringBuffer("");
  BufferedReader reader = null;
  try {
    // initialize buffered reader  
    reader = new BufferedReader(new FileReader(filePath));
    String line = null;
    // read lines of file
    while ((line = reader.readLine()) != null) {
      // append line to string buffer
      fileContentStr.append(line).append("\n");
    }
    // convert string to byte array
    fileContent = fileContentStr.toString().trim().getBytes();
  } catch (IOException e) {
      throw new IOException("Unable to convert file to byte array. " + 
              e.getMessage());
  } finally {
      if (reader != null) {
        reader.close();
      }
  }
  return fileContent;
}

Method 2 : Using Apache Commons IO

org.apache.commons.io.FileUtils class of Apache Commons IO library has a method readFileToByteArray() which takes a java.io.File object representing the file to be read as argument and returns a byte array of contents of file as shown in the code below

public static byte[] convertFileContentToBlob(String filePath) 
              throws IOException {
  byte[] fileContent = null;
  try {
    fileContent = FileUtils.readFileToByteArray(new File(filePath));
  } catch (IOException e) {
      throw new IOException("Unable to convert file to byte array. " +
            e.getMessage());
  }
  return fileContent;
}

Maven dependency for Apache Commons IO library will be

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.15.0</version>
</dependency>

Method 3 : Using java.io.FileInputStream

Create a java.io.FileInputStream object pointing to the file to be converted to byte array.
InputStream has a read() method which takes an empty byte array as argument and fills it with the contents of the file referred by this input stream in byte format.

public static byte[] convertFileContentToBlob(String filePath) 
         throws IOException {
  // create file object
  File file = new File(filePath);
  // initialize a byte array of size of the file
  byte[] fileContent = new byte[(int) file.length()];
  FileInputStream inputStream = null;
  try {
    // create an input stream pointing to the file
    inputStream = new FileInputStream(file);
    // read the contents of file into byte array
    inputStream.read(fileContent);
  } catch (IOException e) {
      throw new IOException("Unable to convert file to byte array. " + 
              e.getMessage());
  } finally {
      // close input stream
      if (inputStream != null) {
        inputStream.close();
      }
  }
  return fileContent;
}

Method 4 : Using java.nio classes

java.nio.Files class has a readAllBytes() method which takes a java.nio.file.Path object pointing to the file as argument and converts it to the byte array containing the contents of the file in byte format.

public static byte[] convertFileContentToBlob(String filePathStr) 
        throws IOException {
  // get path object pointing to file
  Path filePath = Paths.get(filePathStr);
  // get byte array with file contents
  byte[] fileContent = Files.readAllBytes(filePath);
  return fileContent;
}

Method 5 : Using java.io.RandomAccessFile

Class java.io.RandomAccessFile has a method readFully() which takes a byte array as parameter and reads the contents into this array in byte format.
Creating an object of this class is simple, just pass the path of the file along with the mode in which the file is to be opened.
Permissible modes are:
“r” (reading),
“rw” (reading and writing),
“rws” (reading and writing file’s content and its metadata to be written to storage), and
“rwd” (reading and writing file contents to storage).

public static byte[] convertFileContentToBlob(String filePathStr) 
              throws IOException {
   RandomAccessFile randomAccessFile = new RandomAccessFile(filePathStr, "r");
   // initialize byte array with size equal to the size of the file
   byte[] fileContent = new byte[(int)randomAccessFile.length()];
   randomAccessFile.readFully(fileContent);
   randomAccessFile.close();
   return fileContent;
}

Let’s tweak in

  1. For saving file contents in a database column, the column type in the database should be blob and its java type should be byte[].
  2. read() method of java.io.InputStream reads only the number of bytes equal to the size of the byte array. Rest of the bytes are discarded.
  3. readAllBytes() method of java.nio.file.Files class closes the file automatically after the file is completely read. It also closes the file in case of any error.
  4. A java.nio.file.Path object can also be retrieved from toPath() method of java.io.File class as Path path = new File(filePathStr).toPath();
  5. Creation of java.io.RandomAccessFile object may throw a java.io.IllegalArgumentException if the supplied mode is not one among “r”, “rw”, “rws” or “rwd”.
  6. Using the above methods, all text file formats such as txt, xml, html, csv etc., can be converted to a byte array.
    For converting file formats such as audio, video, image use java.io.ByteArrayInputStream in place of java.io.InputStream in Method 3 above.

Conclusion

There are multiple methods available to convert a file to byte array in java.
Each method has its own advantages and limitations, so it is important to choose the one that best fits your needs.
Using Method 1, reading a file into a String, is a simple and straightforward approach but may not be suitable for large files due to memory constraints.
Method 2, using Apache Commons IO, offers more flexibility and options for reading files, making it a good choice for handling different file types and sizes.
Method 3, using java.io.FileInputStream, is another reliable option for converting files to byte arrays, especially for smaller files.
Method 4, utilizing java.nio classes, provides efficient ways to handle file operations, making it a good choice for performance-critical applications.
Lastly, Method 5, using java.io.RandomAccessFile, offers random access to file data which can be useful for specific use cases that require precise control over the file reading process.

In conclusion, the choice of method for converting a file to a blob or byte array in Java depends on various factors such as file size, performance requirements, and the complexity of file operations.
It is important to carefully evaluate these factors and choose the method that best suits your specific needs.

Hope the article was useful.