Determine the size of an InputStream

JavaArraysSizeInputstream

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

I would read into a ByteArrayOutputStream and then call toByteArray() to get the resultant byte array. You don't need to define the size in advance (although it's possibly an optimisation if you know it. In many cases you won't)

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

For InputStream

org.apache.commons.io.IoUtils.toByteArray(inputStream).length()

For Optional < MultipartFile >

Stream.of(multipartFile.get()).mapToLong(file->file.getSize()).findFirst().getAsLong()

Solution 6 - Java

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

Solution 7 - Java

The function below should work with any InputStream. As other answers have hinted, you can't reliably find the length of an InputStream without reading through it, but unlike other answers, you should not attempt to hold the entire stream in memory by reading into a ByteArrayOutputStream, nor is there any reason to. Instead of reading the stream, you should ideally rely on other API for stream sizes, for example getting the size of a file using the File API.

public static int length(InputStream inputStream, int chunkSize) throws IOException {
    byte[] buffer = new byte[chunkSize];
    int chunkBytesRead = 0;
    int length = 0;
    while((chunkBytesRead = inputStream.read(buffer)) != -1) {
        length += chunkBytesRead;
    }
    return length;
}

Choose a reasonable value for chunkSize appropriate to the kind of InputStream. E.g. reading from disk it would not be efficient to have too small a value for chunkSize.

Solution 8 - Java

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: > Returns the number of remaining bytes that can be read (or skipped > over) from this input stream. The value returned is count - pos, which > is the number of bytes remaining to be read from the input buffer.

https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()

Solution 9 - Java

If you know that your InputStream is a FileInputStream or a ByteArrayInputStream, you can use a little reflection to get at the stream size without reading the entire contents. Here's an example method:

static long getInputLength(InputStream inputStream) {
    try {
        if (inputStream instanceof FilterInputStream) {
            FilterInputStream filtered = (FilterInputStream)inputStream;
            Field field = FilterInputStream.class.getDeclaredField("in");
            field.setAccessible(true);
            InputStream internal = (InputStream) field.get(filtered);
            return getInputLength(internal);
        } else if (inputStream instanceof ByteArrayInputStream) {
            ByteArrayInputStream wrapper = (ByteArrayInputStream)inputStream;
            Field field = ByteArrayInputStream.class.getDeclaredField("buf");
            field.setAccessible(true);
            byte[] buffer = (byte[])field.get(wrapper);
            return buffer.length;
        } else if (inputStream instanceof FileInputStream) {
            FileInputStream fileStream = (FileInputStream)inputStream;
            return fileStream.getChannel().size();
        }
    } catch (NoSuchFieldException | IllegalAccessException | IOException exception) {
        // Ignore all errors and just return -1.
    }
    return -1;
}

This could be extended to support additional input streams, I am sure.

Solution 10 - Java

If you need to stream the data to another object that doesn't allow you to directly determine the size (e.g. javax.imageio.ImageIO), then you can wrap your InputStream within a CountingInputStream (Apache Commons IO), and then read the size:

CountingInputStream countingInputStream = new CountingInputStream(inputStream);
// ... process the whole stream ...
int size = countingInputStream.getCount();

Solution 11 - Java

Use this method, you just have to pass the InputStream

public String readIt(InputStream is) {
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        is.close();
        return sb.toString();
    }
    return "error: ";
}

Solution 12 - Java

    try {
        InputStream connInputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int size = connInputStream.available();

int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

InputStream - Android SDK | Android Developers

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChronoXIIIView Question on Stackoverflow
Solution 1 - JavaW. B. ReedView Answer on Stackoverflow
Solution 2 - JavaBrian AgnewView Answer on Stackoverflow
Solution 3 - JavaAndrew DuffyView Answer on Stackoverflow
Solution 4 - JavaakarnokdView Answer on Stackoverflow
Solution 5 - JavaamstegrafView Answer on Stackoverflow
Solution 6 - JavaGnanam RView Answer on Stackoverflow
Solution 7 - JavaSamuelView Answer on Stackoverflow
Solution 8 - JavaSverrir SigmundarsonView Answer on Stackoverflow
Solution 9 - JavaTravis ParksView Answer on Stackoverflow
Solution 10 - JavaRok StrnišaView Answer on Stackoverflow
Solution 11 - JavaCarlos.VView Answer on Stackoverflow
Solution 12 - JavaAshnetView Answer on Stackoverflow