How to create ByteArrayInputStream from a file in Java?

itro picture itro · Jun 27, 2012 · Viewed 97.4k times · Source

I have a file that can be any thing like ZIP, RAR, txt, CSV, doc etc. I would like to create a ByteArrayInputStream from it.
I'm using it to upload a file to FTP through FTPClient from Apache Commons Net.

Does anybody know how to do it?

For example:

String data = "hdfhdfhdfhd";
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());

My code:

public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
    ByteArrayInputStream in;

    return in;     
}

Answer

npe picture npe · Jun 27, 2012

Use the FileUtils#readFileToByteArray(File) from Apache Commons IO, and then create the ByteArrayInputStream using the ByteArrayInputStream(byte[]) constructor.

public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
    return new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
}