My current situation is: I have to read a file and put the contents into InputStream
. Afterwards I need to place the contents of the InputStream
into a byte array which requires (as far as I know) the size of the InputStream
. Any ideas?
As requested, I will show the input stream that I am creating from an uploaded file
InputStream uploadedStream = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
java.util.List items = upload.parseRequest(request);
java.util.Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
uploadedStream = item.getInputStream();
//CHANGE uploadedStreambyte = item.get()
}
}
The request is a HttpServletRequest
object, which is like the FileItemFactory
and ServletFileUpload
is from the Apache Commons FileUpload package.
You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:
http://java.sun.com/javase/6/docs/api/java/io/File.html#length()
If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStream which will grow as required.
When explicitly dealing with a
ByteArrayInputStream
then contrary to some of the comments on this page you can use the.available()
function to get the size. Just have to do it before you start reading from it.From the JavaDocs:
https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()
Use this method, you just have to pass the InputStream
I just wanted to add, Apache Commons IO has stream support utilities to perform the copy. (Btw, what do you mean by placing the file into an inputstream? Can you show us your code?)
Edit:
Okay, what do you want to do with the contents of the item? There is an
item.get()
which returns the entire thing in a byte array.Edit2
item.getSize()
will return the uploaded file size.you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link
Get Bytes from Inputstream
This is a REALLY old thread, but it was still the first thing to pop up when I googled the issue. So I just wanted to add this:
Worked for me. And MUCH simpler than the other answers here.