Ondrej Tokar
Ondrej Tokar

Reputation: 5070

How to get number of elements in byte array?

As everyone already knows, Java allocates the size of array upon declaration. meaning that if I define array like this:

byte[] buffer = new byte[10];

the buffer.length will return 10. However, my question is, how can I find out how many elements are populated. I am populating elements from an InputStream so I never know how many elements will be there.

I know that allocated array positions which are empty will be 0 but what if I am getting zero values from the InputStream as well, mixed together with normal values?

Upvotes: 1

Views: 3017

Answers (4)

Kristijan Iliev
Kristijan Iliev

Reputation: 4987

Lets look at this piece of code:

InputStream inputStream = new FileInputStream(new File("fileName"));
int cntReadBytes = 0;
byte[] bytes = new byte[10];
        while((i = inputStream.read()) != -1) {
            bytes[cntReadBytes] = i;
            cntReadBytes++;
        }
        System.out.println("You have read total: " + cntReadBytes + " bytes" );

as you can see in the while loop condition I make comparison of inputstream return and -1, when the return value is different it means I have more data to read, when it reaches the end of file it will return -1. So the value of cntReadBytes will be the number of iterations, i.e. successfully read bytes.

Or if you are free to use List, you don't have to worry about this.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

You can't. Just store the amount of bytes you have read in a variable. InputStream.read() returns the number of bytes read:

Returns:

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

Upvotes: 2

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62854

You could pre-populate the array with some invalid value that is not expected to be produced by the InputStream. However, this depends on the InputStreams content, so picking a generic default value is not really easy.

Another option for you is to use some collection, like List<Byte> or Set<Byte> (if you need uniqueness) - in this case the number of populated elements will simply be the size of the collection and if you really need an array at the end, you could easily produce one from the content of the collection.

Upvotes: 1

Sebastian S
Sebastian S

Reputation: 4712

You could count the number of bytes passed through the InputStream, e.g. by using Apache Commons CountingInputStream. Or you could extend FilterInputStream yourself, if you don't have Apache Commons.

Upvotes: 0

Related Questions