How to create ByteArrayInputStream from a file in Java?
A ByteArrayInputStream
is an InputStream
wrapper around a byte array. This means you'll have to fully read the file into a byte[]
, and then use one of the ByteArrayInputStream
constructors.
Can you give any more details of what you are doing with the ByteArrayInputStream
? Its likely there are better ways around what you are trying to achieve.
Edit:
If you are using Apache FTPClient to upload, you just need an InputStream
. You can do this;
String remote = "whatever";
InputStream is = new FileInputStream(new File("your file"));
ftpClient.storeFile(remote, is);
You should of course remember to close the input stream once you have finished with it.
This isn't exactly what you are asking, but is a fast way of reading files in bytes.
File file = new File(yourFileName);
RandomAccessFile ra = new RandomAccessFile(yourFileName, "rw"):
byte[] b = new byte[(int)file.length()];
try {
ra.read(b);
} catch(Exception e) {
e.printStackTrace();
}
//Then iterate through b
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));
}
The general idea is that a File would yield a FileInputStream
and a byte[]
a ByteArrayInputStream
. Both implement InputStream
so they should be compatible with any method that uses InputStream
as a parameter.
Putting all of the file contents in a ByteArrayInputStream
can be done of course:
- read in the full file into a
byte[]
; Java version >= 7 contains a convenience method calledreadAllBytes
to read all data from a file; - create a
ByteArrayInputStream
around the file content, which is now in memory.
Note that this may not be optimal solution for very large files - all the file will stored in memory at the same point in time. Using the right stream for the job is important.