Hello guys,

I'm trying to create a method where it takes a InputStream as a parameter, reads the stream and returns the number of characters it contains as an int.

I'm having difficulties with this. I've searched the internet for examples, but i can't find one that helps me with the method i'm creating. Here's my code so far...

public int countNo(InputStream stream)throws IOException
   {
       
       try {
            stream = new InputStream();

            while ((stream = input.read()) != -1) {
                input.write(c);
            }

        } finally {
            if (input != null) {
                input.close();
            }
        }
        return stream;
   }

Can anyone here guide me with completing this method, because i'm having difficulties with it.

Recommended Answers

All 43 Replies

I thought you wanted to count the bytes, not write them out to something else (and, actually, you're trying to write it out to the inputstream you're currently reading, don't you see something wrong with that?). That should be where you look. Don't you think you should be incrementing a variable there, instead?

I thought you wanted to count the bytes, not write them out to something else (and, actually, you're trying to write it out to the inputstream you're currently reading, don't you see something wrong with that?). That should be where you look. Don't you think you should be incrementing a variable there, instead?

Yeah that's what i want to do.

Do you mind if you can give me an example of how to do this (whether a link or a pseudo code)?

That code i wrote was formed through using various examples over the net. I've read about the InputStream, but there seems to be so many different examples on the net/textbook and all of the seem to be complicated.

Or can i get a simple written break down of doing the method please?

Do you know how to declare an int variable?

Do you know how to increment it?

Well, declare one before the while loop, and increment it within the while loop. And, do nothing else inside the while loop.

If you want to read from a file and count how many characters are in it, use FileReader or FileInputStream, not InputStream, since you cannot open a File with InputStream. Then use a while loop like they said, incrementing a counter for each byte you read. The final value of the counter is how many characters were in the file.

Also, note that FileInputStream is not recommended for reading characters. I'm not sure why, but a wild guess would be that it deals with the fact that chars in Java are 16 bits, but chars on your computer might be represented as 8 bits. This might be completely wrong, feel free to do some research on your own.

[FileReader] Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

Sorry, but his question started

create a method where it takes a InputStream as a parameter

and not, necessarily, anything to do with a file.

If you want the size of a file, simply use the length() method.

Thanks for the replies guys! I'm just coming back to this program today.

BestJewSinceJC, i'm using an inputStream, but your reply has been useful anyways. Thanks.

Do you know how to declare an int variable?

Do you know how to increment it?

Well, declare one before the while loop, and increment it within the while loop. And, do nothing else inside the while loop.

Hi masijade,

I've just done this and edited the code...

public int read(byte[] b) throws IOException
   {
       int number = 0;
       try {
            number = new FileInputStream("Hello");
            int c;

            while ((c = number.read()) != -1) {
                number++;
            }
        } finally {
            if (number != null) {
                number.close();
            }
        }
        return number;
   }

The code gives me a compile error saying it "found java.io.FileInputStream but expected int". Do you know where i'm going wrong with this? Also am i on the right track with this method so far?

Still need help with this.

Hi masijade,

I've just done this and edited the code...

public int read(byte[] b) throws IOException
   {
       int number = 0;
       try {
            number = new FileInputStream("Hello");
            int c;

            while ((c = number.read()) != -1) {
                number++;
            }
        } finally {
            if (number != null) {
                number.close();
            }
        }
        return number;
   }

The code gives me a compile error saying it "found java.io.FileInputStream but expected int". Do you know where i'm going wrong with this? Also am i on the right track with this method so far?

_____________________________________________________

Well, my friend... you don't need to SEARCH more; instead, you should think about it a bit. Just sit down and take a piece of paper and think how you want to approach this problem.
Think as a human being if you want to count the characters in a long word, how would you do that?
Simply, you would start with the first character and in you mind, subconciously, you'd increment by one whenever you encounter the next character.
(as an example: count the characters in "ASLKFMNWLENFASLDTERWEF" :P)

The error you're currently encountering is quite obvious:
When you write "int number = 0; number = new FileInputStream("Hello");", it's NOT allowed to initialize an as a FileInputStream object.

Like the guys above said, you should initialize an integer to zero (in your example, it's "number"). Then start the loop with the first character, go to the last one and keep incrementing unless the string finishes.
So, if you're forced to use InputStream as the parameter, you can use BufferedReader to read the InputStream. For instance, if 'isr' is your InputStream, it's something like BufferedReader br = new BufferedReader(isr);
And converting the inputstream into String (using br.readLine()), you can then count the number of characters in the String. (I really hope you can figure that out now. Actually, we guys have left nothing virtually nothing to figure out).

I hope I helped.

P.S.: I realise I made my post too long. Sorry for that.

Thanks a lot abbie! I appreciate the comment, I'll work something out from it.

Like the guys above said, you should initialize an integer to zero (in your example, it's "number"). Then start the loop with the first character, go to the last one and keep incrementing unless the string finishes.
So, if you're forced to use InputStream as the parameter, you can use BufferedReader to read the InputStream. For instance, if 'isr' is your InputStream, it's something like BufferedReader br = new BufferedReader(isr);
And converting the inputstream into String (using br.readLine()), you can then count the number of characters in the String. (I really hope you can figure that out now. Actually, we guys have left nothing virtually nothing to figure out).

I'm still having trouble with this...

I've done everything (i think) required, but i'm just not getting the code to compile. Here's my code...

public int read(byte[] b) throws IOException {
       
       try {
            int number = 0;
            InputStream is = new InputStream(b);
            BufferedReader br = new BufferedReader(is);

            while ((b = br.read()) != null) {
                number++;
            }
        } finally {
            if (number != null) {
                number.close();
            }
        }
        return number;
   }

When i compile the code it highlights "InputStream is = new InputStream(b);" and says it can't be instantiated.

Can someone point me to where i'm going wrong with my code? I know that the "InputStream is = new InputStream(b);" line is wrong; i'm trying to use InputStream as a parameter, but i'm doing it all worng. I just need know if i'm in the right direction and what i need to sort out.

InputStream, as the Java API doc makes very clear, is an abstract class; it's definition is incomplete and you cannot instantiate it with new. It's purpose in life is to define a standard set of operations that any byte-oriented input stream should implement. As also explained in the API doc, it has a number of subclasses that you can instantiate, including one that is based on a byte[] array. So, you can declare is as an InputStream reference variable, but you have to instantiate one of its subclasses to get a real input stream to use as its value.
Finally, it's the input stream you need to close, not your integer.
oh, and ps, read the API doc for InputStream.read() to find out what it returns (hint: it's not a byte array) and what it does when it reaches end-of-file (hint: it doesn't return null).

InputStream, as the Java API doc makes very clear, is an abstract class; it's definition is incomplete and you cannot instantiate it with new. It's purpose in life is to define a standard set of operations that any byte-oriented input stream should implement. As also explained in the API doc, it has a number of subclasses that you can instantiate, including one that is based on a byte[] array. So, you can declare is as an InputStream reference variable, but you have to instantiate one of its subclasses to get a real input stream to use as its value.
Finally, it's the input stream you need to close, not your integer.
oh, and ps, read the API doc for InputStream.read() to find out what it returns (hint: it's not a byte array) and what it does when it reaches end-of-file (hint: it doesn't return null).

Thanks, i'm looking into it now.

Hi JamesCherrill,

I've edited my code...

public int read(byte[] b) throws IOException {
       
       try {
            int number = 0;
            InputStream is = new ByteArrayInputStream(b);
            BufferedReader br = new BufferedReader(is);

            while ((b = br.read()) != null) {
                number++;
            }
        } finally {
            if (number != null) {
                is.close();
            }
        }
        return number;
   }

Some things here...

1) I've used a ByteArrayInputStream to initialise is as an InputStream, but i don't know how to "instantiate one of its subclasses to get a real input stream to use as its value" - I need help on that.

2) I get an error in the "BufferedReader br = new BufferedReader(is);" line, saying it cannot find symbol contructor BufferedReader. Could that be due the problem i'm having in 1?

3) InputStream.read() returns the next byte of data or -1 if the end of the stream is reached. Is that right? Are you telling me this because there is something wrong in my code? Otherwise i don't understand what you mean.

^^^^^^

1. You got this bit right! ByteArrayInputStream is a subclass of InputStream, ie it's a "kind" of InputStream. You have created an instance of ByteArrayInputStream, and that is a suitable object to set is to.
2. Personally I'd forget the bufferedreader bit, just read directly from is. You can worry about optimising it later.
3. Yes, you got that right as well. In your code you read(), but you assign the result to b, which is a byte array, not an integer as required by the API. Your code also tests for end-of-file by looking for a null value, when it should look for -1.

^^^^^^

I understand your impatience, but I have a life to live here. People are arriving for dinner in 15 mins (it's 18:45 here) and I have to go now. I'll check this thread again tomorrow

1. You got this bit right! ByteArrayInputStream is a subclass of InputStream, ie it's a "kind" of InputStream. You have created an instance of ByteArrayInputStream, and that is a suitable object to set is to.
2. Personally I'd forget the bufferedreader bit, just read directly from is. You can worry about optimising it later.
3. Yes, you got that right as well. In your code you read(), but you assign the result to b, which is a byte array, not an integer as required by the API. Your code also tests for end-of-file by looking for a null value, when it should look for -1.

Thanks for the feed back.

I understand your impatience, but I have a life to live here. People are arriving for dinner in 15 mins (it's 18:45 here) and I have to go now. I'll check this thread again tomorrow

Don't worry, you do your thing.

I'll be working on this code until i get it right.

In your inital post, you were to take an intpustream as the argument and count the number of bytes in it. Now you're talking a byte array? Well, if in that case the purpose is to return the number of bytes in the byte array smply return b.length.

Somehow or another, you seem to keep slipping sideways whenever you "correct" something, rather than coming closer to your goal.

Go back to the very start of this thread, and the code that was posted there, then, go through the first few posts changing only those parts of that code that you were told you needed to change and you will have your solution as of post #6.

JamesCherrill,

I've edited the code...

public int read(byte[] b) throws IOException {
       
       try {
            int number = 0;
            InputStream is = new ByteArrayInputStream(b);

            while ((b = number.read()) != -1) {
                number++;
            }
        } finally {
            if (number != null) {
                is.close();
            }
        }
        return number;
   }

When i compile it, it highlights the "while ((b = number.read()) != -1)" line, saying the...

int cannot be dereferenced

Do you know what the problem is?

In your inital post, you were to take an intpustream as the argument and count the number of bytes in it. Now you're talking a byte array? Well, if in that case the purpose is to return the number of bytes in the byte array smply return b.length.

Somehow or another, you seem to keep slipping sideways whenever you "correct" something, rather than coming closer to your goal.

Go back to the very start of this thread, and the code that was posted there, then, go through the first few posts changing only those parts of that code that you were told you needed to change and you will have your solution as of post #6.

Yes i'm taking an InputStream, and trying to read the stream and return the number of characters it contains as an int.

I'll look back at my code.

BTW look at the code above, is that in the right direction?

If your talking about how you declared the int and incremented it, then yes, if your talking about passing in byte arrays and creating inputstreams, then, well, why do you think I told you to start over at the beginning of the thread?

Also, are you to return the number of bytes, or the number of charatcers? If this is a UTF character stream, those two will be two different things.

masijade and other,

To make it clear to you, here's the question i'm trying to answer...

Write a method called countNo which takes an InputStream as a parameter, reads the stream and returns the number of characters it contains as an int. Any >IOExceptions which might occur in the method should be passed back to the method's caller.

Am i going about this the right way?

Also, are you to return the number of bytes, or the number of charatcers? If this is a UTF character stream, those two will be two different things.

It's the number of characters.

Okay masijade,

I went back to the code in the first post and edited like i was instructed the first few replies....

public int countNo(InputStream stream)throws IOException
   {
       
       try {
           int number = 0;

            while ((stream = number.read()) != -1) {
                number++;
            }

        } finally {
            if (number != null) {
                stream.close();
            }
        }
        return number;
   }

When i compile it, it highlights the "while ((stream = number.read()) != -1)" line and says the "int cannot be dereferenced".

Do you know what the problems with this?

You have those backward. I don't think you intend to read() from 'number'.

You have those backward. I don't think you intend to read() from 'number'.

What am i supposed to read from?

Sorry, Ezzaral, i don't understand what you mean.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.