Requirement

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 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 ( "

" ) ; } // 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 ; } 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("

"); } // 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 Library



org.apache.commons.io.FileUtils

readFileToByteArray

java.io.File

import org.apache.commons.io.FileUtils ; 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 ; } import org.apache.commons.io.FileUtils; 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; }

class of Apache Commons Library has a methodwhich takes aobject representing the file to be read as argument and returns a byte array of contents of file as shown in the code below:

Maven dependency for Apache Commons library(v 2.5) will be

<dependency>

<groupId>commons-io</groupId>

<artifactId>commons-io</artifactId>

<version>2.5</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 ; } 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.



import java.nio.file.Files ; import java.nio.file.Path ; import java.nio.file.Paths ; 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 ; } import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; 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 ; } 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; }

Also Visit : How to insert image in database and retrieve it using java

Let’s tweak in :

For saving file contents in a database column, the column type in the database should be blob and its java type should be byte[ ] . 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. 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. 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(); 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”. 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.

Like this: Like Loading...