Java: convert a file to a byte array, then convert byte array to a file.

In this post, I will show you how to convert a file to a byte array and then convert a byte array to a file.

To convert a file to byte array, ByteArrayOutputStream class is used. This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().

To convert byte array back to the original file, FileOutputStream class is used. A file output stream is an output stream for writing data to a File or to a FileDescriptor.

The following code has been fully tested.

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class genFile {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
        File file = new File("java.pdf");
 
        FileInputStream fis = new FileInputStream(file);
        //System.out.println(file.exists() + "!!");
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
 
        //below is the different part
        File someFile = new File("java2.pdf");
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }
}

Why would someone like to convert a file to byte array?

There are various applications of this conversion. For example, convert file into byte to save into database, transfer file to other system using web service, etc.

Similarly, you can convert an image to byte array, see this post.

UPDATE(2015/12/16):
There is a very convenient method from com.google.common.io.Files - toByteArray(). Check out some examples here.

References:

1. ByteArrayOutputStream Java Doc
2. FileOutputStream Java Doc

Category >> Real Methods  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. rp on 2011-2-4

    How the byte pass to the bmp image , its give error with imaje.io methods pls tell me that how it solve!!!!!!!!!!!!!!!!!!!11

  2. Daison on 2012-2-3

    Nice code. I like it. I will use it . Thanks.

  3. Daison on 2012-2-7

    Sir , how can i read large size of file upto 2 GB?

  4. Admin on 2012-2-9

    If file size is large, I don’t think it even should be read to a byte array in memory.

  5. Babli on 2012-7-6

    Thanks a lot. this code solves my problem which I was facing for last 1 week and looking for solution in the net. Thanks a lot again….

  6. Steve on 2012-7-20

    I tried this but the file created was padded with trailing nulls making it unusable. How do I get a file without trailing nulls?

  7. Thusitha dissanayaka on 2012-10-25

    Very good code, This is very use full for me, Thanks lot …

  8. 李志平 on 2012-11-6

    It used to be a big confusion for me.thank you very much.

  9. jorge on 2012-11-20

    good!

  10. Bennet on 2013-2-7

    Awesome and a simple example! Keep the good work up!

  11. Zuby Doby on 2013-5-6

    i want ot convert audio file into bytes then convert butes array into audio file plz help

  12. dddddddd on 2013-12-3

    NOOB

  13. Eloy on 2014-3-6

    I want to do the same (with Android)… have you found any way??

  14. […] did some gagoogling; https://community.oracle.com/message/5341572 Java: convert a file to a byte array, then convert byte array to a file. Reply With […]

  15. Dhanush on 2015-2-18

    Can u please tell me how to convert doc files to pdf

  16. Ponpandian N Nateshan on 2015-5-25

    save the doc files as pdf.
    Open the doc file,
    Click File -> Save As,
    In the Save as type: drop down select PDF

  17. Ali Khan on 2016-2-7

    Best example… Searching for it last 3 days… Many Thanks.. 🙂

  18. Ezhil on 2017-9-5

    Could u explain how to write the ByteArray (.docx file w already stored in DB as ByteArray ) which am getting from DB into PDF Document

Leave a comment

*