Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the size of an InputStream

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.

like image 259
ChronoXIII Avatar asked Jul 13 '09 13:07

ChronoXIII


People also ask

How do you define InputStream?

InputStream , represents an ordered stream of bytes. In other words, you can read data from a Java InputStream as an ordered sequence of bytes. This is useful when reading data from a file, or received over the network.

How do I find the length of a FileInputStream?

3. Using FileChannel#size() method. Another option is to obtain a file input stream for the file in a file system and get the associated file channel. Then you can use the size() method that returns the current size of the channel's file, measured in bytes.


1 Answers

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:

InputStream inputStream = conn.getInputStream(); int length = inputStream.available(); 

Worked for me. And MUCH simpler than the other answers here.

Warning This solution does not provide reliable results regarding the total size of a stream. Except from the JavaDoc:

Note that while some implementations of {@code InputStream} will return * the total number of bytes in the stream, many will not.

like image 88
W. B. Reed Avatar answered Sep 28 '22 05:09

W. B. Reed