javaarraysbytebufferbytearrayinputstream

How to create ByteArrayInputStream from a file in Java?


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;     
}

Solution

  • 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));
    }