Easy Copying Using Commons.IO library

Recently, I had run into a piece of work that had to write a multipart file in a disk location. The multipart file is injected from a web page using HTML file input. The basic Java Development Kit (JDK) provides a lot of functions for File Operations in java.io package. We can read/write files using this package. I used FileOutputStream to write the multipart file in the favoured location. The following code snippet reveals the write operation using java.io.

public void writeFile(MultipartFile multipartFile) {
    try {
        // Create the file in the required destination location
        File file = new File("E:/sample.png");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        // Write the multipart file in specified location
        fileOutputStream.write(multipartFile.getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
    }
    catch(Exception e) {
    e.printStackTrace();
    }
}

Though the above code copies the incoming file (image/text/XML) correctly in the required location, the performance will be poor if the file size becomes MBs. In my case, I faced time out exception during write operation since the file is too big. I discussed this issue with my colleagues and found that, Commons IO package yields a better solution.

Commons IO is a library of utility functions to assist IO operations. Instead of writing the file with FileOutputStream, I copied the entire file using a single utility provided by Commons IO library.

import org.apache.commons.io.FileUtils;
...
...
// Create the file in the required destination location
File file = new File("E:/sample.png");
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);

Because this utility only copies the file, it would not take much time even if the file size is larger. Not only “copyInputStreamToFile”, the package has different functions for copy operation based on the input. We can use this library to make the IO operations more efficient.

ABOUT THE AUTHOR

Am a foodie, I enjoy coding and open to learn new tech ideologies. Am a big lover of Rajesh kumar tamil novels.
Author Lekshmi Am a foodie, I enjoy coding and open to learn new tech ideologies. Am a big lover of Rajesh kumar tamil novels.  

Looking for awesomeness!

Join Us