Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;      } 
like image 991
itro Avatar asked Jun 27 '12 10:06

itro


People also ask

What is ByteArrayInputStream in java?

ByteArrayInputStream , of the Java IO API enables you to read data from byte arrays as streams of bytes. In other words, the ByteArrayInputStream class can turn a byte array into an InputStream.

What is the difference between FileInputStream and ByteArrayInputStream?

The InputStream is an abstract class and ByteArrayInputStream is a concrete class of InputStream and offers its own implementation of the abstract idea given by (InputStream), In Addition : A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.


1 Answers

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)); } 
like image 125
npe Avatar answered Sep 28 '22 03:09

npe